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
Related
I am using Apache POI 3.17 to create xlsx files and filling it with data from the db. The file gets created fine but when I try to open it, I get 'incompatible format' error even though when I inspect the file, I can see that it is a Microsoft spreadsheet file. I looked at here,here and here and tried all these examples but didn't help and I don't know where the problem is. Here is my file creation code:
File excelFile = new File("C:\\myFile.xlsx"); //a new file to be created
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(rowIndex);
Cell cell;
//some font and style creation
for(String eachHeader : headers) {
cell = row.createCell(cellIndex);
cell.setCellValue(eachHeader);
cell.setCellStyle(headerStyle);
cellIndex++;
}
//some more row and cell creation
try {
//finally try to write all this content into the excel file
OutputStream out = new FileOutputStream(excelFile);
workbook.write(out);
out.close();
logger.debug("Worksheet created: " + excelFile.getAbsolutePath());
}catch(Exception exc) {
logger.error("Error occured while creating or writing to the excel file: " + exc.getMessage());
}
Again, the file is created fine with some data in it as I can see that the size is not 0, but just cannot open it, why??
I write java class to read xls file, class works fine when I read many xls file, but doesn't work if I try to read a file that I receive, and I have to read this file :(
public int readData() {
try {
excelFile = new File(excelFullFileName);
fis = new FileInputStream(excelFile);
workBook = new HSSFWorkbook(fis);
if (sheetName != null && !sheetName.equals("")) {
sheet = workBook.getSheet(sheetName);
} else {
sheet = workBook.getSheetAt(0);
sheetName = sheet.getSheetName();
}
sheetRecords.setSheetName(sheetName);
When set workBook catch exception
Exception: org.apache.poi.hssf.record.RecordInputStream$LeftoverDataException: Initialisation of record 0x203(NumberRecord) left 4 bytes remaining still to be read.
If I try to past e copy records on a new xls, java code works fine.
I think it is a file issue, but how I can read original xls file??
Help me please :(
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?
I gotta add info to a already existing excel file. The reader I built works wonderfully,but every tutorial I've seen just shows how to edit an already existing file or creating a new one. I just need to add 4 cells with info at the end of the file (if the existing file has 2 rows of data I'll add the new data in the third row), and every time it kicks me with an error when trying to access the file, and I'm using the same method to access the file in the reader, and that one works, it doesn't make sense.Here's the code so far:
try{
FileInputStream Album=new FileInputStream(new File("songs.xls"));
HSSFWorkbook workbook=new HSSFWorkbook(Album);
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
int last=sheet.getLastRowNum();
Row row =sheet.createRow(last+1);
Cell cell1=row.createCell(0);
cell1.setCellValue(name);
Cell cell2=row.createCell(1);
cell2.setCellValue(artist);
Cell cell3=row.createCell(2);
cell3.setCellValue(duration);
Cell cell4=row.createCell(3);
cell4.setCellValue(genre);
try {
FileOutputStream out=new FileOutputStream(new File("c:/Users/twhit/Documents/U/2016/1ro 2016/POO/IntelliJ/Proyecto1POO/src/Canciones.xls"));
workbook.write(out);
out.close();
}
catch (Exception e){
e.printStackTrace();
}
}
catch(Exception e){
e.printStackTrace();
}
I am using Apache POI for writing into .xlsx file. I can write into .xlsx file but I am unable to append new content. How can I append new content in the .xlsx file?
My Code is:
public static void write(){
try {
Workbook[] wbs = new Workbook[]{new XSSFWorkbook()};
Workbook workbook=wbs[0];
org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet();
System.out.println(sheet.getSheetName());
Row row = sheet.createRow(2);
for(int i=0;i<10;i++){
Cell cell=row.createCell(i);
cell.setCellValue("Sun System");
}
FileOutputStream fout=new FileOutputStream("D:/Test.Xlsx");
workbook.write(fout);
fout.close();
} catch (Exception e) {
}
}
The first thing U've to do :
When you're working with Excel 2007 format, its more wise to use XSSF-Implementations, because you've used abstract implementations. Always remember this when using any implementation.
To append to an existing file you need to reach the end of the rows in that particular workbook sheet. This can be achieved by:
int rows = sheet.getPhysicalNumberOfRows(); // or sheet.getLastRowNum();
After that you can create new cells with the XSSF- Implementation classes. For more information refer to this page
You should open the existing file instead of creating a new one if you want to append, see also this stackoverflow question:
Edit existing excel files using jxl api / Apache POI
You are creating a new workbook each time this is run youd want to create a FileInputStream with a file path to the excel file and then use that input stream to get the XSSF workbook you want to edit
FileInputStream fis = new FileInputStream(filePath);
XSSFWorkbook workBook = new XSSFWorkbook(fis);
then in order to get a specific sheet you simply just use the .getSheet or getSheetAt methods that are apart of workBook. then create and set cells