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??
Related
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 am trying to create the csv file with data as follows
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
String fileLocation = null;
try {
// Set the header columns name for worksheet
createHeader(workbook, sheet);
// populate the data
createWorkbookRows(ker, sheet, kerList, AerList);
String tempDir = System.getProperty("java.io.tmpdir");
File file = new File(tempDir);
fileLocation = file.getAbsolutePath() + FileSystems.getDefault().getSeparator() + "MyData.csv";
FileOutputStream outputStream = new FileOutputStream(fileLocation);
workbook.write(outputStream);
}catch(Exception e){
}
With the above code I am able to generate the csv file, but when I try to open the file the below error it is showing
When I click on yes it is showing the data properly in excel file.
I have verified the csv file by opening in Notepad++ also it is showing in non understandable language instead of comma seperated.
Please suggest how can I solve the above issue.
POI writes a binary Excel file. Your extension "csv" is wrong. It should be "xlsx" because you use XSSFWorkbook.
I have an Excel spreadsheet that has the first sheet designated for the raw data. There are 3 more sheets that are coded to transform and format the data from the raw sheet. The fifth sheet has the final output.
How can I use Java:
load the data from the CSV file into the first sheet of the excel file?
save the data from the 5th sheet into the new CSV file.
Also, if the original CSV has thousands of rows, I assume the multi-sheet transformations would take some time before the 5th sheet gets all the final data - is there a way to know?
I would follow this approach:
Load the specific .csv file and prepare to read it with Java
Load the .xlsx file and change it according to your requirements and the data that you get from the .csv file. A small example of how an excel file is changed with Apache POI can be seen below:
try
{
HashMap<Integer, ArrayList<String>> fileData; // This for example keeps the data from the csv in this form ( 0 -> [ "Column1", "Column2" ]...)
// Working with the excel file now
FileInputStream file = new FileInputStream("Data.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(file); // getting the Workbook
XSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
AtomicInteger row = new AtomicInteger(0);
fileData.forEach((key, csvRow) ->
{
//Update the value of the cell
//Retrieve the row and check for null
HSSFRow sheetRow = sheet.getRow(row);
if(sheetRow == null)
{
sheetRow = sheet.createRow(row);
}
for (int i = 0; i < csvRow.size(); i++)
{
//Update the value of cell
cell = sheetRow.getCell(i);
if(cell == null){
cell = sheetRow.createCell(i);
}
cell.setCellValue(csvRow.get(i));
}
});
file.close();
FileOutputStream outFile =new FileOutputStream(new File("Data.xlsx"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
After saving the .xlsx file, you can create the .csv file by following this question.
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