append data into xlsx file through java - java

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

Related

Java Writing Data to Excel - WorkbookFactory

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

xlsx file created with apache poi cannot be opened

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??

Open EXISTING xls in Apache POI

I have an existing file (C:\wb.xls) that I want to open and make changes to. How in Apachie POI do you open an existing file? All the documentation that I find has to go with creating a new file. And if you know, how do you insert a new row at the top of the xls file or how to autoformat column widths?
Use one among the following
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(xlFileAddress));
OR
Workbook wb = WorkbookFactory.create(new File(xlFileAddress));
OR
Workbook wb = WorkbookFactory.create(new FileInputStream(xlFileAddress));
and then use wb for creating/reading/updating sheets/rows/cell whatever you want. For detail visit here. This will definitely help you.
Did you try reading the Apache POI HowTo "Reading or modifying an existing file"? That should cover you...
Basically, what you'll want to do is taken from the QuickGuide eg this for loading a File
Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));
Sheet s = wb.getSheetAt(0);
// Get the 11th row, creating if not there
Row r1 = s.getRow(10);
if (r1 == null) r1 = s.createRow(10);
// Get the 3rd column, creating if not there
Cell c2 = r1.getCell(2, Row.CREATE_NULL_AS_BLANK);
// Set a string to be the value
c2.setCellValue("Hello, I'm the cell C10!");
// Save
FileOutputStream out = new FileOutputStream("New.xls");
wb.write(out);
out.close();

Writing to existing excel file using POI

I have used POI to read from / write to excel sheets.When writing to a new sheet using POI,it worked.But, when i am trying to write in a existing excel workbook using POI, it doesnt worked.how can i correct this issue?
workBook = getWorkbookSheet(workBookName);
sheet1 = workBook.getSheetAt(1);
sheet2 = workBook.getSheetAt(2);
while(sheetStart<sheet1.getLastRowNum() + 1)
{
HSSFRow rowSheet1 = sheet1.getRow(sheetStart);
HSSFCell cellSheet1 = rowSheet1.getCell(4);
if(cellSheet1.getStringCellValue().trim().equals(valY))
{ cellSheet1.setCellValue("N");
}
else
//do nothing
sheetStart++;
}
fileOutSheet1 = new FileOutputStream(sheet1.getSheetName());
workBook.write(fileOutSheet1);
fileOutSheet1.flush();
fileOutSheet1.close();
fileOutSheet1 = new FileOutputStream(sheet1.getSheetName()); seems not correct. you should give the path of workbook instead of sheet1.getSheetName. because you are writing the whole workbook even after a single cell content change.
for example it should be like
FileOutputStream fileOut = new FileOutputStream("C:\\MyWorkbook.xlsx");
wb.write(fileOut);
fileOut.close();
for detail visit here

Create Excel reports by programming from templates

I'm using "Apache POI" to generate Excel report. I've a well designed Excel template. I want to create a report by filling the data into predefined locations of the template. That is to say, I do not want to care about the formats of the report. Is that possible? Could you give me some instructions?
I got my answer. I can use the "Cell Naming" utility in Microsoft Excel and then use the following code to locate the cell and do something.
CellReference[] crefs = this.getCellsByName(wb, cName);
// Locate the cell position
Sheet sheet = wb.getSheet(crefs[0].getSheetName());
Row row = sheet.getRow(crefs[0].getRow());
Cell cell = row.getCell(crefs[0].getCol());
// Write in data
cell.setCellValue(cellRegion.getContent());
"cName" is the cell's name predefined in Microsoft Excel.
You can have a look at jXLS, I think that's what you are looking for.
It takes a Excel as template and you can write a Java app to fill the data:
http://jxls.sourceforge.net/
You can load you template file like any other XLS. And then make the changes you want to the specific cells and write it out into another file.
Some sample code:
Load file
InputStream inputStream = new FileInputStream ("D:\\book_original.xls");
POIFSFileSystem fileSystem = new POIFSFileSystem (inputStream);
HSSFWorkbook workBook = new HSSFWorkbook (fileSystem);
do stuff
HSSFSheet sheet1 = workBook.getSheetAt (0);
Iterator<Row> rows = sheet1.rowIterator ();
while (rows.hasNext ())
{
Row row = rows.next ();
// do stuff
if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
System.out.println ("Row No.: " + row.getRowNum ()+ " " + row.getCell(0).getNumericCellValue());
HSSFCell cell = row.createCell(0);
cell.setCellValue("100");
}
Write the output to a file
FileOutputStream fileOut1 = new FileOutputStream("D:\\book_modified.xls");
workBook.write(fileOut1);
fileOut1.close();
You may also take a look at Xylophone. This is Java library built on top of Apache POI. It uses spreadsheet templates in XLS(X) format and consumes data in XML format.

Categories

Resources