I am trying to create a Java package to interface with Excel, so I am using the org.apache.poi libraries. I've found the documentation on the POI site that shows the following:
Reading and Rewriting Workbooks
(truncated)
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
When I attempt to create a Workbook object, I get errors that it doesn't know the type. The documentation above doesn't show the import statements, but if I'm reading these POI docs correctly, I should be able to import org.apache.poi.ss.usermodel.Workbook, (and it's distinctly possible that I'm wrong because I'm very new to Java) but trying all of the following import statements all result in errors for the Workbook type.
import org.apache.poi.*;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
I should note that I'm using Eclipse Neon for this, and the editor is not complaining that it can't find the packages, so I'm not sure where the issue lies.
Workbook wb = WorkbookFactory.create(inp);
The actual error I'm getting in the editor is that "Workbook cannot be resolved to a type", and the same error for WorkbookFactory.
So the TL;DR is that the POI docs show that Workbook is an Interface in org.apache.poi.ss.usermodel and that WorkbookFactory is a class in the same usermodel package, but I can't figure out how to import/use them correctly.
EDIT:
The build time error I receive is
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Workbook cannot be resolved to a type
WorkbookFactory cannot be resolved
at spreadsheet.conversion.ConvertXLSXtoCSV.main(ConvertXLSXtoCSV.java:31)
The message I posted before was the editor popup... I was able to take a screenshot:
EDIT: Posting the full code, because, why not. (The multiple import statements
were just trying things out, mostly in desperation.)
package spreadsheet.conversion;
import java.text.ParseException;
import org.apache.poi.*;
import org.apache.poi.ss.*;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.InputStream;
public class ConvertXLSXtoCSV {
private static String inputfilename = "";
private static String outputfilename = "";
private static int debug = 0;
private static void test(String arg) {
System.out.println(arg);
}
public static void main(String[] args) throws ParseException, Exception {
if (args.length != 1) {
throw new Exception("Requires 1 parameter. Usage: ConvertXLSXtoCSV <filename>");
}
inputfilename = args[0];
if(debug==1) {
test(inputfilename);
}
InputStream inp = new FileInputStream(inputfilename);
Workbook wb = WorkbookFactory.create(inp);
}
Any help is appreciated.
As unhelpful to others as this may be, it's the solution I've come up with so I'm posting it as an answer. Many thanks for the comments about this, but I've always hated Eclipse, and decided to go with NetBeans IDE instead. It was extremely trivial to right click on Libraries, Add JAR/Folder, and select the POI jar files, and it (and the integrated Maven install) took care of the details and it worked perfectly right off the bat and resolved all library dependencies.
I believe this due to jar file corrupted ( most probably during download for the first time). Here what you can do.
You can delete all poi folder in maven repository .m2/repository/org/apache/poi then you can update maven by Right Click on the project > Maven > Update Project. Eclipse will automatically download the dependencies and auto rebuild the workspace.
im facing the same thing like yours and manage to get it clean.
Related
i'm trying to use itext (5.5.13) in IBM i (AKA iseries, Power, long ago AS/400). It could be done embedding java code into RPG ILE procedures, or executing plain java. We use Apache POI for Excel for a while, and it works well. We are testing itext now, but some issue persist yet.
Given that, I'm trying to test itext in plain java into IBM i. I prepared a very simple example, taken from listing 1.1 of "Itext in action", and run it. It seems to work well, but nothing is generated. No pdf file results. And no error appears while running.
am i forgetting something? are there some other aspects to take in account?
here is the code:
package QOpenSys.CONSUM.Testjeu;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class test1{
public static final String filePdf = "/QOpenSys/MyFolder/Testjeu/PdfRead1.pdf";
public static void main(String[] args)
throws DocumentException, IOException
{
///QOpenSys/MyFolder/Test/WrkBookRead1.pdf
//pdfDocument = new_DocumentVoid()
Document pdfDocument = new Document();
//pdfWriter = get_PdfWriter( pdfDocument: pdfFilePath);
PdfWriter.getInstance(pdfDocument, new FileOutputStream( filePdf ));
// jItxDocumentOpen( pdfDocument );
pdfDocument.open();
//pdfParagraph = new_PdfParagraphStr( PhraseString );
Paragraph jItxParagraph = new Paragraph("Hola, pdf");
//addToDocPg = jItxDocumentAddParagraph( pdfDocument: pdfParagraph );
pdfDocument.add(jItxParagraph);
//jItxDocumentClose( pdfDocument );
pdfDocument.close();
}
}
Solved. As said before, there was a first issue: it seems java function ran well because not errors/warnings were visible at qshell. It was false: errors were sent to outq, and were available at spool file. Being reviewed, it was a simple classpath issue. It required a full day to figure out what failed locating classpath.
Now it works, and pdf is created. I ran it on qshell, declaring environment variables for java_home (three jvm are executed concurrently by several applications), for classpath, and a couple required for tracing. Classpath declares first my class and secondly itext classes. Remaining classes comes from JRE. I have a full list of classes loaded by class loader. I hope it will help to find what fails in our embedded RPG ILE call to itext.
I am new in Java, and I am trying to use tablesaw (https://jtablesaw.github.io/tablesaw/) to do some data visualization, but I get an IOException during the import of the file (see code below).
I have tried various functions and methods of tablesaw (read/readmultiple and various builder for the XlsxReaderOptions). The xls import export is not well documented (yet), but I tried to re-use the jUnit Test I saw in the github.
I have also checked the file path, and java.io.File find it. So I guess the mistake is in the code below.
Does anyone here use tablesaw and can show me the correct way to import/export excel file ? Or through another dataviz library ?
import tech.tablesaw.api.Table;
import tech.tablesaw.io.xlsx.*;
[...]
public class App
{
[...]
private static Table getTable(String FileName)
{
XlsxReader reader = new XlsxReader();
XlsxReadOptions options = XlsxReadOptions.builder(FileName).build();
Table tab = reader.read(options);
return tab;
}
The error message :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException
at com.testPack.excelRun.App.getTable(App.java:30)
at com.testPack.excelRun.App.main(App.java:22)
Thank you for any help you could provide !
You can try solved your issue with following import:
import java.io.IOException;
And handle your sub with add IOException like this:
private static Table getTable(String FileName)throws IOException{
XlsxReader reader = new XlsxReader();
XlsxReadOptions options = XlsxReadOptions.builder(FileName).build();
Table tab = reader.read(options);
return tab;
}
Also put IOException in your main
I am learning to program in java. I have programmed in other languages. I have tried import java.net.*; at the start of my code file. But it ghosts out. I have looked in my External Libraries directory and it is not there. I found that java.net was deprecated in 201x <-- some recent year. I am using jdk 10. I am using IntelliJ IDE. I have gotten some import statements to work.
I saw on github that they took over hosting oracle classes that were deprecated at Oracle.
I know I have to use the classpath command if I put the .jar or the .zip file containing the class in another directory. I have searched my laptop and i don't have any other .jar or .zip files other than specific other programs I have installed which also don't contain the java.net class (e.g. Aptana Studio 3)
I am using Mac with OS Sierra.
package com.robinhoodcomputer.myfirstprojects;
import java.io.FileReader; <<-- these import ok
import java.io.*;
import java.net.*; <<--- these don't import
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Myreader {
public static void main(String[] args) throws Exception {
int intVal;
char myChar;
String st;
File file = new File("/java/file");
BufferedReader br = new BufferedReader(new FileReader(file));
// FileReader fr = new
FileReader("/java/HelloWorld/resources/file.txt");
while ((intVal = br.read()) != -1) {
myChar = (char) intVal;
System.out.print(myChar);
}
myHostName = getLocalHost(); <<-- this doesn't show being available
}
}
I have searched and cannot find any articles that actually do anything but explain how to connect to the class file and that you have to import it in your code. No one talks about getting the java.net class itself.
I found one reference to jdk.net in an oracle jdk 10 API specification page.
What am I suppose to use to get the IP address using a hostname in java these days??
thx
P.S. I know this code really doesn't have anything to do with networking, most of it is just reading a file and displaying what's in the file. I wanted to use this code file just to try getting an IP address also. My question is mainly just about making the import statement to work. thx
Your imports are grayed out, since you do not call any method of the imported libraries. As soon as you start using the getLocalHost() method properly, the import will not be grayed out any more. This is a convenience functionality of your IDE it seems.
getLocalHost() is a method of InetAddress and can't be just called without such an instance.
Look at this question for how to use this:
java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?
Before I start, I'd like to say that I've spent 4 hours today, 6 hours yesterday and 3 hours before that researching this issue. I've read every post I can find, followed every instruction to the letter, restarted my project, reinstalled my IDE (Netbeans) and even fresh installed my OS, and I haven't found a single piece of helpful advice, so I figured I needed to ask for help.
AND YES, I HAVE PUT THE FILE IN THE RIGHT LOCATION
... As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents. I've checked and changed and defaulted the root directory many times. PLEASE don't tell me to just use an exception handler. The file the program reads in is guaranteed to exist and contain something.
So here's my question:
I'm trying to input and read from a file, however, the result is always that the file can't be found. Here's an example of my code (and it really is down to this atm):
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
FileReader inputFile = new FileReader(args[0]);
}
}
Here are two of the errors I get (I also get Filenotfound errors, but I don't think I need to add that):
Exception in thread "main" java.lang.RuntimeException: Uncompilable source
code - unreported exception java.io.FileNotFoundException; must be caught or
declared to be thrown
at project2.Project2.main(Project2.java:14)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 1 second)
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at project2.Project2.main(Project2.java:24)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 0 seconds)
That's it. The file name comes from the arguments, and I have tried every possible variation of the name. I have tried naming the file outside of the arguments, as just the file name itself and also with an explicit file path.
Using a scanner won't let me read anything in. FileReader won't even run.
The text file has no special formatting or characters, and I've used the one I was supplied with and multiple that I hand typed just in case there was an issue with the one I was given. I have also made sure that ".txt" is never read or used twice (I keep my extensions on, anyway).
I have checked attributes and permissions of all files and the Netbeans program itself. I've also made sure that the text files were included in the project build.
I am not using any additional code right now, as I can't do anything until I'm sure that I can read in a file, and then output one as well. I also know that the text files aren't corrupt because I can read them in Python just fine, however, I have to use Java and I have to use Netbeans.
This is a new problem for me, I've always been able to read in files fine, and I've exhausted my options. I really need some help if anyone has any ideas.
The first exception (java.lang.RuntimeException: Uncompilable source
code) is thrown because the code that you have shown us is not valid java source code.
new FileReader(args[0]) is declared as throwing FileNotFoundException and according to the rules of the java language you either have to catch this exception or declare your main method as throwing this exception.
One way to fix this problem is to write your main method like this:
public static void main(String[] args) throws FileNotFoundException {
FileReader inputFile = new FileReader(args[0]);
}
It seems that you have solved this issue because the second exception (java.util.NoSuchElementException: No line found) is thrown by the Scanner.nextLine() method if you try to read past the end of the file.
Since you have not shown any code using the Scanner class it's hard to tell where to problem is in this case.
As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents.
Don't do that. You are creating a mess with files that will be hard to cleanup. If you want to know which file your program is reading then adding the following simple line tells you the exact path and filename:
System.out.println(new File(args[0]).getAbsolutePath());
Have you ever tried with a simple, minimal example like this:
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
System.out.println(new File(args[0]).getAbsolutePath());
FileReader inputFile = new FileReader(args[0]);
try (Scanner s = new Scanner(inputFile)) {
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
}
}
}
It should print out the name of your file with the complete path and then the contents of the file line by line.
I don't think Java is messing around with you a not found file is a not found file, please elaborate more in this issue by screens of files and directories you are working on.
I would like you to consider take a look at the following:
FileReader
Path of projects on Netbeans
I hope this helps may the code be with you.
This reads a file with no problem. I'll assume you're running JDK 8.
/**
* Read a file example
* User: mduffy
* Date: 4/21/2017
* Time: 7:48 AM
* #link http://stackoverflow.com/questions/43529600/java-nothing-will-read-in-this-file
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Project2 {
public static void main(String[] args) {
if (args.length > 0) {
BufferedReader reader = null;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(args[0]))) {
bufferedReader.lines().forEach(System.out::println);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Usage: Project2 <file>");
}
}
}
Here's the input file I used:
line1
line2
hello, michael
line 4
Here's the output I got:
java Project2 .\src\main\resources\test.txt
line1
line2
hello, michael
line 4
Process finished with exit code 0
import java.io.File;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class SampleTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
pkg.close();
}
}
Both import statement still tells me it does not exist.
I tried:
Adding poi-bin-3.15-20160924.zip to Libraries|Add JAR/Folder, it has all the jar including the poi-ooxml-3.15.jar
Adding folder of poi-bin-3.15-20160924 to the same place
Which is the common solutions to all the duplicate questions but it doesn't solve my problem, so how do I add the Apache Poi correctly which I can import successfully in my code.
Or can someone just give me a fully working Netbean project folder which already has the Apache Poi inside.
UPDATE
My friend gave me an idea of will my import understand if its nested inside a folder. So after I added all the jar directly to my libraries, it worked. So now my question is how do I modify my import statement so that they know I am referring to Apache Poi(folder)|poi-bin-3.15-20160924.zip|poi-ooxml-3.15.jar