Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to check 30 sheets in an excel file. Every sheet has a maximum of 7 rows and plenty of columns.
I need to update every row (if a certain condition is true) by adding 32 new columns after the last existing column, then save the file.
So I need to be able to do both read and write on my excel file from the same piece of code, then to save my changes updating the original excel file (using the same file name).
I really think Apache Poi is the best solution when it comes to managing excels in Java. You might want to have a look at these examples provided by Apache Poi itself about this topic (the url may change slightly over time). This article also may provide an hint for the solution you're asking for.
You can create a new Workbook (the Java Object representing your excel) using WorkbookFactory as follows:
Workbook workbook = WorkbookFactory.create(new FileInputStream(excelFilePath));
where excelFilePath is (obviously) the Path of the excel file you want to update.
You can now do whatever you want with your Workbook, hurray! You can both read and change all its content and (eventually) write new one! Note that all the changes to your Workbook are NOT actually going to affect your excel file. You're editing the Workbook Java Object, not the actual excel file. In a sense, your Workbook is initially created based on your excel file content, then it is totally independent from it.
Once you're done editing your Workbook, you can save it overriding your initial excel file (in a way, you're now updating your excel file with all your changes) as follows:
FileOutputStream outputStream = new FileOutputStream(excelFilePath);
workbook.write(outputStream);
workbook.close();
outputStream.close();
and you're done! Simple and effective!
Here it is some code that may suit your needs:
public static void main(String[] args) throws EncryptedDocumentException, IOException {
// Step 1: load your excel file as a Workbook
String excelFilePath = "D:\\Desktop\\testExcel.xlsx";
Workbook workbook = WorkbookFactory.create(new FileInputStream(excelFilePath));
// Step 2: modify your Workbook as you prefer
Iterator<Sheet> sheetIterator = workbook.sheetIterator(); // Getting an iterator for all the sheets
while (sheetIterator.hasNext()) {
Iterator<Row> rowIterator = sheetIterator.next().rowIterator(); // Getting an iterator for all the rows (of current sheet)
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// Put here your internal logic to understand if the row needs some changes!
int cellsn = row.getLastCellNum() == -1 ? 0 : row.getLastCellNum();
for (int j = cellsn ; j < cellsn + 32 ; ++j) {
row.createCell(j, CellType.STRING).setCellValue("New column after the last existing one n°" + (j - cellsn + 1));
}
}
}
// Step 3: update the original excel file with all your amazing changes!
FileOutputStream outputStream = new FileOutputStream(excelFilePath);
workbook.write(outputStream);
workbook.close();
outputStream.close();
}
Some final notes:
Do not call the method create(java.io.File file) instead of create(java.io.InputStream inp) while using WorkbookFactory and creating your Workbook, it will lead to problems when saving your file as it's discussed on this post.
I really don't know the reason why you initially add the tag "selenium" to your question but if you're thinking to use some spider-code to "manually" open and edit your excel file, please don't. This solution is as horrible as HSSF is (did you get the joke?).
If you're using .xlsx excel files, you may want to use Apache Poi XSSF objects (as XSSFWorkbook, XSSFRow and XSSFCell). More about XSSF vs HSSF on this post.
Finally, here it is the explicit list of all libreries needed in order for my code to run (they're a lot, do not panic): Apache Poi 4.1.2, Apache Poi Ooxml 4.1.2, Apache Poi Ooxml Schemas 4.1.2, XmlBeans, Commons Codec, Commons Collections4, Commons Compress and Commons Math3. If you're using Maven, just add to your dependencies file the following lines:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
And that's all, hope it helps! Good work!
Related
I have one excel template placed in my application's configuration folder. Now while downloading that excel template, I am trying to edit it's data and existing formulas using POI api. I am able to edit data easily.
How can I edit existing formulas? The formula which I am trying to edit, is attached with more than 1000 cells, so instead editing every cell and updating formula, I am trying to update that formula itself.
I am using following code to get workbook object
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File("ExcelTemplate.xlsx")));
XSSFSheet sheet = workbook.getSheetAt(5);
for(int i = 2; i<174; i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(0);
cell.setCellValue("My Data");
}
FileOutputStream output_file =new FileOutputStream(new File("UpdatedExcelTemplate.xlsx"));
workbook.write(output_file);
output_file.close();
Problem which I am facing is as following:
I have one sheet (say sheetA) in which I am inserting values at run time. And I am referring that list of data in another sheet (say sheetB) as drop down for any cells. Now as per data range in sheetA, my formula should get change.
I have written a code to access .xlsm file but it fails to do so. I have tried the same file using both XSSFWorkBook and the Generic WorkBook which is done using WorkBookFactory.
Scenario 1:
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(new File(
"/filename.xlsm"));
Error:
The supplied spreadsheet seems to be an Encrypted .xlsx file. It must be decrypted before use by XSSF, it cannot be used by HSSF.
So I left the generic way of reading the file and used XSSF.
Scenario 2:
XSSFWorkbook workBook = new XSSFWorkbook(new FileInputStream(new
File("/fileName.xlsm")));
Error:
org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
Both the scenarios do work on some .xlsm files. Properties and data with working and non working files are the same.
Can someone help in fixing this.?
Promoting a comment to an answer... You need to upgrade your version of Apache POI!
You can view the Apache POI changelog here, and see quite how many changes there have been since 3.9 came out 3 years ago. It's quite a number of pages of fixes! And you need at least one of those...
I'm generating an Excel file in Java with POI 3.2 (Latest version I can use for my client).
Here is my code. As you can see I'm using HSSF because I need to make a XLS file.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Reporting");
sheet.setColumnWidth(250,250);
HSSFRow Row;
HSSFCell Cell;
//Content part (doesn't matter)
IWDResource resource = WDResourceFactory.createCachedResource(
wb.getBytes(),
"workbook.xls",
WDWebResourceType.XLS);
wdContext.currentContextElement().setXls(resource);
Now after I've downloaded the XLS file, I want to open it but the file seems to be corrupt.
Image on link: http://tinyurl.com/nop52sh
When I'm pressing 2 times on 'Don't send', de excell file opens in correct form.
Any idea why?
Don't call wb.getBytes(), it doesn't do what you want. From the getBytes() javadoc
Method getBytes - get the bytes of just the HSSF portions of the XLS file. Use this to construct a POI POIFSFileSystem yourself.
Instead, if you want the overall xls file as a byte array, do
ByteArrayOutStream baos = new ByteArrayOutStream();
wb.write(baos);
byte[] xlsBytes = baos.toByteArray();
Finally, Apache POI 3.2 is ancient, over 5 years old now! You really ought to upgrade, see the changelog for an idea of all the bugs fixed since then
This question already has answers here:
Copying Excel Worksheets in POI
(6 answers)
Closed 3 years ago.
I have one excel file with single sheet (abstract model). Now I want to copy the sheet to another existing workbook. How can I do this?
For processing regular styles and data we could iterate through each cells.
But if we have formula enabled cell,non editable cells, merged cell then this is the better solution to go for:
I have tried something like copying sheets but it didn't worked.
In addition with that i need to copy a sheet in which there are some non editable cells and formula enabled cells too.
This solution worked for me:
1)copy the entire workbook
2)delete unnecessary sheets
3)add your new sheets to above book
//input source excel file which contains sheets to be copied
file = new FileInputStream("C:\\SamepleTemplate.xlsx");
workbookinput = new XSSFWorkbook(file);
//output new excel file to which we need to copy the above sheets
//this would copy entire workbook from source
XSSFWorkbook workbookoutput=workbookinput;
//delete one or two unnecessary sheets, you can delete them by specifying the sheetnames
workbook.removeSheetAt(workbook.getSheetIndex(workbook.getSheet(" your sheet name ")));
//if you want to delete more sheets you can use a for to delete the sheets
for (int index=0;index<=5;index++)
{
workbook.removeSheetAt(index);
}
//To write your changes to new workbook
FileOutputStream out = new FileOutputStream("C:\\FinalOutput.xlsx");
workbookoutput.write(out);
out.close();
I am interested and would like to learn more about java , how to write into existing excel sheets / manipulating the existing data. I was wondering if you could give me an idea on how to edit an existing excel file and save it using the jxl api / Apache POI
or perhaps give me a sample program on how to edit some data in an existing excel file and then save it
Thanks in advance !!
The tutorials here are very helpful and well-written. They use an external JAR developed by the Apache POI project.
Here's an simple example of editing one cell:
InputStream inp = new FileInputStream("wb.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt([sheet index]);
Row row = sheet.getRow([row index]);
Cell cell = row.getCell([cell index]);
String cellContents = cell.getStringCellValue();
//Modify the cellContents here
// Write the output to a file
cell.setCellValue(cellContents);
FileOutputStream fileOut = new FileOutputStream("wb.xls");
wb.write(fileOut);
fileOut.close();
Hope it helps
One very important tip that I learned the hard way.
Open the OutputStream only after you have completed writing to your excel workbook. Zabbala's example is spot on and shows this correctly. If you open the OutputStream any earlier, your changes would not be written to the file after your program exits and you would be scratching your head as I did.
I refresh the formulas with another tab for this I use the next sentence
HSSFSheet worksheetse = workbook.getSheetAt(0);
worksheetse.setForceFormulaRecalculation(true);
but it's necesary that you apply the method setForceFormulaRecalculation for all the tabs that have the formulas.
Sorry for my English
Hello i have the same problem than neXGen. But strangely if i open the file with openoffice, it works!
Edit: perhaps i found a solution, put this after changing the values:
HSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);