I recently attempted to rename my project in Eclipse using refactoring, and when I did I ran into many errors. I think I resolved all of them, but now my program is getting stuck while reading in a .xlsx file.
File file = new File("C://Users/user1/ExcelFile.xlsx");
if(!file.getName().endsWith("xlsx")) {
JOptionPane.showMessageDialog(null,
"Please select an Excel file (.xlsx)",
"Error", JOptionPane.ERROR_MESSAGE);
} else {
XSSFWorkbook workbook = null;
try {
// Find the workbook instance for XLSX file
workbook = new XSSFWorkbook(file);
} catch (IOException e) {
Logger.getLogger(
XLSXHandler.class.
getName()).log(Level.SEVERE, null, e);;
}
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = workbook.getSheetAt(0);
// reading sheet into taskList
tasks = readInTasks(mySheet);
}
The problem area seeems to be in the "workbook = new XSSFWorkbook(file);" line because in the debugger, workbook is filled with null values. In my build path, I have included the following .jar files:
poi-3.15-beta1.jar
poi-ooxml-3.15-beta1.jar
poi-ooxml-schemas-3.15-beta1.jar
xmlbeans-2.6.0.jar
commons-codec-1.10.jar
jxl.jar
stax-api-1.0.1.jar
Any ideas?
Related
I am trying to write an excel file using java. I'm looking for just simply a column with one username per row right now, and then will build upon this later once I understand what is going a bit better. I get a zip file instead of the expected excel file, and it contains docProps, _rels, xl, and [Content_Types].xml. I don't understand how to open this zip file as though it is an excel file. I have not had luck finding the answer as all the tutorials I see show it to be a straight forward excel file, not a zip file. Is it a configuration I'm missing or is it to do with linux?
Here's my code, and what I end up with:
private void createExcelSheet(Assignment assignment) throws FileNotFoundException {
String excelFilePath = Configuration.DIRECTORY_ROOT+"/tests/"+assignment.getAssn_number()+"/gradebook-"+assignment.getAssn_number();
int rowNum = 0;
int col = 0;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet(assignment.getAssn_number()+" Grades ");
XSSFRow row = spreadsheet.createRow(rowNum);
Cell cell;
for (User user : userService.getUsers() ) {
row = spreadsheet.createRow(rowNum);
cell = row.createCell(rowNum);
cell.setCellValue(user.getStudent_id());
rowNum++;
}
try (FileOutputStream fos = new FileOutputStream(excelFilePath)) {
workbook.write(fos);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I am trying to add some data to, already existing file which I created with; copyFileNIO(fromFile, toFile) method. To add data to already existing file I am using this code block:
try {
copyFileNIO(fromFile, toFile);
System.out.println("Copy file is done.");
// Creating file object of existing excel file
File xlsxFile = new File(toFile);
System.out.println("ok");
// Creating input stream
InputStream inputStream = new FileInputStream(xlsxFile);
System.out.println("okkk");
// Creating workbook from input stream
Workbook wb = WorkbookFactory.create(inputStream);
System.out.println("okkkk");
// Reading first sheet of excel file
Sheet sheet = wb.getSheetAt(0);
// Getting age cell of first row from the sheet
Cell cell = sheet.getRow(1).getCell(3);
// Updating the cell value with new data
cell.setCellValue(30);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Copy file is done.");
}
However, Workbook is giving error, I tried also XSSF its not working. I do not know what causes this. You can see ambda$7 exception:
at application.Sbt.lambda$7(Sbt.java:492) -> which leads Workbook wb = WorkbookFactory.create(inputStream);
I added some System.out.println as can seen on code: output of these methods are
Copy file is done.
ok
okkk
Exception ...
How can i solve this problem ? Thank you
I confirmed my file exists and patch is correct. Changed inputstream and workbook to -> Workbook wb = WorkbookFactory.create(new File(toFile)); Still same error
full error message and stack trace
at org.apache.poi.poifs.filesystem.FileMagic.valueOf(FileMagic.java:177)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:309)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:277)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:255)
at application.Sbt.lambda$7(Sbt.java:491)
Apache POI -> 5.2.3
I have a code which writes to the excel file using apache poi api. The problem is it everytime writes the new data to the file and not append the data. can you please help me here. Here is my code.
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelWrite {
public static void write(AddExcel addExcel){
try {
XSSFWorkbook workbook = new XSSFWorkbook("NG.xlsx");
XSSFSheet worksheet = workbook.createSheet("Scrap Data");
int lastRow = worksheet.getLastRowNum();
System.out.println(lastRow);
Row row = worksheet.createRow(++lastRow);
row.createCell(2).setCellValue(addExcel.getArtistName());
row.createCell(3).setCellValue(addExcel.getItemName());
row.createCell(6).setCellValue(addExcel.getOriginalPrimaryMarket());
row.createCell(7).setCellValue(addExcel.getAvgResalePrice());
row.createCell(8).setCellValue(addExcel.getPriceChangedFromPrimaryMarket());
row.createCell(9).setCellValue(addExcel.getHighestAvgBid());
row.createCell(10).setCellValue(addExcel.getLastSoldPrice());
row.createCell(11).setCellValue(addExcel.getSecondayMarketVolume());
row.createCell(12).setCellValue(addExcel.getSecondarySales());
row.createCell(13).setCellValue(addExcel.getPrimarySales());
row.createCell(14).setCellValue(addExcel.getDateCreated());
row.createCell(16).setCellValue(addExcel.getInstagramURl());
row.createCell(17).setCellValue(addExcel.getTwitterURL());
FileOutputStream out = new FileOutputStream(new File("NG.xlsx"));
workbook.write(out);
out.close();
System.out.println("Write Successfully.");
}
catch(IOException io){
System.out.println(io.getMessage());
System.out.println(io.getStackTrace());
}
}
}
The problem is that each time you run your code, you always create a brand new XSSFWorkbook and so a brand new excel file, deleting and overriding the existing one.
It doesn't matters you're calling worksheet.getLastRowNum(); it will always return -1 because your XSSFWorkbook will always be empty.
If you want to update an existing excel file (appending new rows to it), you MUST create your XSSFWorkbook by loading that existing excel file. You're code is broken because with the line
workbook = new XSSFWorkbook();
you're creating a brand new XSSFWorkbook which is totally unrelated to the excel file you want to update. You HAVE TO use instead:
Workbook workbook = WorkbookFactory.create(new FileInputStream(toUpdateExcelFilePath));
You might want to have a look at this post for more details: how to update an existing excel file in Java.
According to my test (I used 4.1.2 version from maven repository) when you use createSheet it produce an exception:
java.lang.IllegalArgumentException: The workbook already contains a sheet named 'Scrap Data'
With the getSheet() method you can grab the existing sheet. If it does not exist you will be get a null then you can create a new sheet with the required name.
XSSFWorkbook workbook;
try {
File file = new File("NG.xlsx");
workbook = new XSSFWorkbook();
if(file.exists()) {
FileInputStream fs = new FileInputStream(file);
workbook = new XSSFWorkbook(fs);
}
String sheetName = "Scrap Data";
XSSFSheet worksheet = workbook.getSheet(sheetName);
if(worksheet == null) {
worksheet = workbook.createSheet(sheetName);
}
... //other code unchanged
} catch(Exception io){
io.printStackTrace();
}
NOTE: I changed the file reading code a little bit because I got errors and the documentation says the following:
* Note - if the Document was opened from a {#link File} rather
* than an {#link InputStream}, you <b>must</b> write out to
* a different file, overwriting via an OutputStream isn't possible.
I am trying to write data to excel sheet using Apache POI.I am using TestNG framerwork and eclipse IDE. Program is executing successfully without any error.But when I click refresh on my project source, excel sheet is not coming. Please tell me how will I see my generated excel sheet.
My code is as below:
public class Test {
public static void main(String args[]) {
try {
FileOutputStream fos = new FileOutputStream("User.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("worksheet");
HSSFRow row1 = worksheet.createRow((short) 0);
HSSFCell cell1 = row1.createCell((short) 0);
cell1.setCellValue("abc");
HSSFCell cell2 = row1.createCell((short) 1);
cell2.setCellValue("123");
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please check your project's root directory. It should be there by default. If you have specified the working directory in your run configuration -> arguments, you should check that folder. Besides, you can always get the complete file path in Java.
System.out.println(new File("User.xls").getAbsolutePath());
try this way to create file
FileOutputStream out =
new FileOutputStream(new File("User.xls"));
This file will be stored in your class directory folder.
Ex: (Test.java is stored in (c://Workspace//src//Test.java) , the file also will store in same path c://Workspace//src//User.xls")
While trying to open an excel using ApachePOI I get
org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file: 'C:\Users\mdwaipay\AppData\Local\Temp\poifiles\poi-ooxml-1570030023.tmp'
I checked. No such folder is being created. I am using Apache POI version 3.6.
Any help? A similar code was running fine in a different workspace. At loss of thoughts here.
Code:
public Xls_Reader(String path) {
this.path=path;
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
}
catch (Exception e)
{ e.printStackTrace();
}
}
Why are you taking a perfectly good file, wrapping it in an InputStream, then asking POI to have to buffer the whole lot for you so it can do random access? Life is much better if you just pass the File to POI directly, so it can skip about as needed!
If you want to work with both XSSF (.xlsx) and HSSF (.xls), change your code to be
public Xls_Reader(String path) {
this.path = path;
try {
File f = new File(path);
workbook = WorkbookFactory.create(f);
sheet = workbook.getSheetAt(0);
} catch (Exception e) {
e.printStackTrace();
}
}
If you only want XSSF support, and/or you need full control of when the resources get closed, instead do something like
OPCPackage pkg = OPCPackage.open(path);
Workbook wb = new XSSFWorkbook(pkg);
// use the workbook
// When you no longer needed it, immediately close and release the file resources
pkg.close();