Edit existing excel files using jxl api / Apache POI - java

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);

Related

How to update an excel file in java? [closed]

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!

Can not read .xlsm file - POI

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

POI 3.2 Excel file Data has been lost

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

How to print excel file from java?

First Question on the community!
Let me explain a little the question.
I have a user interface, that allows me to create an excel file. And I want to add at that ui the a "print Document" button. This button is supposed to allow the user to print that excel document. So what I need is a way to call the windows printing dialog for that file, so the user can print the file.
I have read http://docs.oracle.com/javase/tutorial/2d/printing/printable.html, But I can not find the way of telling the printing dialog what file to print.
Thanks in advance!
I think Apache POI is the best thing for you. Code syntax is like
POIFSFileSystem filesystem = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wrkbook = new HSSFWorkbook(filesystem );
HSSFSheet sheet = wrkbook.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
//Keep on doing your manipulation.
More about Apache POI.

Converting java file to excel spread sheet

First of all thanks for the previous help.
What I want to do is the following.
Is to collect information through a small program that can capture in Java and writes it to a file which I have done.
Then to have this information passed to a preformatted excel spread sheet.
In the spread sheet it reads this data that is written and displays it in different tables and graphs.
Is this possible to automatically code or do I have to write to a csv file, from the csv file manually copy to an excel template?
If anybody has come across a solution to my problem I would appreciate a steer in the right direction
Hey try ths code in servlet or in JSP.
This will convert simple excel sheet on which you can do further operations..
response.setContentType("application/vnd.ms-excel");
PrintWriter out = response.getWriter();
try {
out.println("\tId \tName");
out.println("\t1\tabc");
out.println("\t2\txyz");
out.println("\t3\tpqr");
} finally {
out.close();
}
here ..
response.setContentType("application/vnd.ms-excel");
specify the excel sheet to be generated..
all "\t" separates new cell in the excel sheet.
On your requirement basis you can also change this code with database or any...
It's a duplicate of How to read and write excel file in java
you can use this API: http://poi.apache.org/
Or if you write one text file with tab separation between fields and save with (.XLS) extension, excel should read it. But off course the better solution is to use Apache POI HSSF.

Categories

Resources