I have an application in Java and I manage Excel workbooks with JXL API.
I would like to create a new sheet in an existing workbook that already has a sheet (so I want to create a second sheet).
But I don't want to erase the existing workbook and sheet, just add a new one and add data in it.
How can I achieve that ?
The following code I have tried doesn't work for me, it erases the existing workbook :
//this is my existing workbook that I want to open and not erase
//I can't use getWorkbook for WritableWorkbook
WritableWorkbook target = Workbook.createWorkbook(new File("C:/Novas/template_test.xls"));
//I want to add a new sheet after the existing sheet
WritableSheet writeSheet = target.createSheet("Sheet 2", 1);
Label label = new Label(0,0,"test");
writeSheet.addCell(label);
target.write();
target.close();
Finally I have found the solution. here is my updated code :
Workbook source = Workbook.getWorkbook(new File("C:/Novas/template_test.xls"));
//just use the createWorkbook method that uses an existing Workbook and will copy it
WritableWorkbook target = Workbook.createWorkbook(new File("C:/Novas/template_copy.xls"),source);
//then create the new sheet after the existing that will not be erased
WritableSheet writeSheet = target.createSheet("Sheet 2", 1);
Try following :
1 - Instead of using Workbook.createWorkbook, use Workbook.getWorkbook to load the existing workbook
2 - Get the sheets length and then incrementing it by 1 to define the new sheet's position in existing workbook
WritableWorkbook target = Workbook.getWorkbook(new File("C:/Novas/template_test.xls"));
WritableSheet writeSheet = target.createSheet("Sheet 2", target.getSheets().length+1);
....
Ref : http://jexcelapi.sourceforge.net/resources/javadocs/current/docs/jxl/Workbook.html
Hope it helps!
Related
I use a template file containing 2 tables on first sheet. I need to perform 2 operations on first sheet.
There is Locations data table column headers(ex. sr.no, Location and related data fields) in which I need to use XSSFWorkbook so that I may shift rows down according to size of locations.
There is Devices Table, in which I need to use streaming api i.e. SXSSFWorkbook object
I created workbook object using XSSFWorkbook, shifted rows down and then tried to cast workbook into SXSSFWorkbook. But it throws error while in execution
java.lang.IllegalArgumentException: Attempting to write a row[11] in the range [0,30] that is already written to disk.
If I first create workbook obj using SXSSFWorkbook, it is not possible to create
XSSFWorkbook from it. Can someone please suggest how it can be done.
I tried :
FileInputStream inputStream = new FileInputStream(new File(filePath));
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheet("Sheet1");
// First shift rows down - WORKS FINE
sheet.shiftRows( tab1HeaderRowNum + 1, sheet.getLastRowNum(), locationRecordsSize - 1);
// Copy style of row on new rows - WORKS FINE
for(int i = 1; i < locationRecordsSize; i++){
sheet.copyRows(tab1HeaderRowNum , tab1HeaderRowNum , (tab1HeaderRowNum + i), cellCopyPolicy);
}
// Create new SXSSFWorkbook
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(workbook);
SXSSFSheet sxssfSheet = sxssfWorkbook.getSheet("Sheet1");
if(sxssfSheet.getRow(rowNum) == null){ // rowNum is of row which is newly added using shiftRows
row = sxssfSheet.createRow(rowNum); // Error Occurs Here
}else{
row = sxssfSheet.getRow(rowNum);
}
Im using Apache POI 3.15
I am trying to write a excel file using Apache POI package. Here is the code snippet:
String basePath = "/home/aman/Desktop";
String fileName = "result.xls";
File file = new File(basePath, fileName); //File not null. checked.
OPCPackage pkg = OPCPackage.openOrCreate(file); //pkg not null. checked.
Workbook wb = new XSSFWorkbook(pkg); //GenerateReport.java:63
I get the following error:
Exception in thread "main" java.lang.NullPointerException
at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:382)
at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:155)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:186)
at amazon.category.database.GenerateReport.generateExcel(GenerateReport.java:63)
at amazon.category.database.MerchantAdoptionStats.processAdoptionStats(MerchantAdoptionStats.java:197)
at amazon.category.database.MerchantAdoptionStats.main(MerchantAdoptionStats.java:386)
Any help appreciated.
I found this example at the tutorial site:
here
You could try this approach.
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
I hit my head against this one for a while myself. The trick is whether or not the file exists prior.
//if file is .xls
Workbook workbook;
if(file.exists) {
NPOIFSFileSystem fs = new NPOIFSFileSystem(file);
workbook = new HSSFWorkbook(fs.getRoot(), false);
}
else {
workbook = new HSSFWorkbook();
}
//if file is .xlsx
Workbook workbook;
if(file.exists) {
OPCPackage pkg = OPCPackage.open(file);
workbook = new XSSFWorkbook(pkg);
}
else {
workbook = new XSSFWorkbook();
}
The trick appears to be (and this doesn't look like it is documented well), that you create the workbooks off of the file system or package objects only if the file exists prior. If you want a new file, then don't use the file system or package objects to create your workbooks.
If everything is what it looks like, you should not be able to build an XSSFWorkbook on an .xls file, since it is a class to model .xlsx files. You should use WorkbookFactory.create() instead of that, which is a factory method that will return the appropiate Workbook implementation for each case
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();
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
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