Creating new sheet using Apache POI removes all the existing sheets - java

I trying to add new sheet to an existing excel file using Apache poi library as in the below code.
FileOutputStream fileOut = new FileOutputStream(new File(BASE_PATH+outputFile));
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Splitted Rules");
Set<String> tags = outputRules.keySet();
int i = 0;
for (String tag : tags) {
List<String> rules = outputRules.get(tag);
for (String rule : rules) {
Row row = sheet.createRow(i++);
row.createCell(0).setCellValue(tag);
row.createCell(1).setCellValue(rule);
}
}
wb.write(fileOut);
fileOut.close();
wb.close();`
The problem is that all the sheets in the file is deleted and only the new sheets exist.
What is this problem ?

The comments already hint at the solution.
The code above creates a new workbook and overwrites any existing file.
If you want to append a sheet to an existing workbook use the WorkbookFactory.create method (or the XSSFWorkbook constructors with the appropriate argument) to create the workbook based on the existing excel file.

Related

Is it possible to read the data from different sheets in a same xlsx file?

i am using the Apache POI to read an xlsx file. i can able to read the Sheet1 data. But when try to read the Sheet2 i am getting the Sheet1 data only.
String strPath = "..\\Test.xlsx";
File excelFile = new File(strPath);
FileInputStream fis = new FileInputStream(excelFile);
// we create an XSSF Workbook object for our XLSX Excel File
XSSFWorkbook workbook = new XSSFWorkbook(fis);
Sheet sheet1= workbook.getSheetAt(0);
Sheet sheet2= workbook.getSheetAt(1);
When you call getSheetAt(i), it returns a XSSFSheet object, which implements the Sheet interface under org.apache.poi.ss.usermodel. Consider the block of code below:
XSSFSheet sheet = workbook.getSheetAt(0);
System.out.println(sheet.getRow(0).getCell(0).getStringCellValue());
sheet = workbook.getSheetAt(1);
System.out.println(sheet.getRow(0).getCell(0).getStringCellValue());
The code above should print the content of cell A1 for the first two sheets on your document. I did it myself with a test file and it worked.
Here's an example of how to do that using apache POI https://www.callicoder.com/java-read-excel-file-apache-poi/
This is the part where they're iterating over the different sheets
// 1. You can obtain a sheetIterator and iterate over it
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
System.out.println("Retrieving Sheets using Iterator");
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
System.out.println("=> " + sheet.getSheetName());
}

Not able to write data in xlsx file using java?

I Have a data stored in variables and then i want to write my data to excel file(.xlsx).
(i.e) I use automation testing tools like selenium to get data from webpage and i store it in variable which i want to wrie in xlsx file
After a lot of google search I found many of users uses list or objects to write into .xlsx file.
I created a list and add my variable to that list and using looping statements (for loop) i checked whether my data is stored in list by printing it.
Then I created XSSFWorkbook and XSSFSheet and XSSFRow and XSSFCell to write data.
I write a cell by using setCellValue method to my cell.
My code successfully creates a xlsx file and sheet in it
but after execution i could not able to find any data in it.
Source code:
ArrayList<String> head = new ArrayList<String>();
head.add("Register Number");
head.add(subject1);
head.add(subject2); //subject1 and subject2 are variable i created
System.out.println(head.get(1)); //To check if my list has value
XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("/home/st.xlsx");
for (int i = 0; i < head.size(); i++)
{
XSSFRow Row = sheet1.createRow(1);
XSSFCell cell = Row.createCell(1);
cell.setCellValue(head.get(1));
sheet1.autoSizeColumn(1);
}
workbook.write(fileOut);
fileOut.close();
I expect my code add data to my file.
Main thing is During execution when i try to open my .xlsx file it has data in it.
But after the complete execution i get with the empty xlsx file.
I don't know why i'm getting this and What wrong in my code?
Thanks in advance!
ArrayList<String> head = new ArrayList<String>();
head.add("Register Number");
head.add(subject1);
head.add(subject2); // subject1 and subject2 are variable i created
System.out.println(head.get(0)); // To check if my list has value
System.out.println(head.get(1)); // To check if my list has value
System.out.println(head.get(2)); // To check if my list has value
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = wb.createSheet("Sheet1");
for (int r = 0; r < head.size(); r++)
{
XSSFRow row = sheet1.createRow(r);
XSSFCell cell = row.createCell(0);
cell.setCellValue(head.get(r));
sheet1.autoSizeColumn(0);
}
// Write this workbook to a FileOutputStream.
FileOutputStream fileOut = new FileOutputStream("/home/st.xlsx");
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
More info here:
https://gist.github.com/madan712/3912272

Unable to read the excel file using Apache POI - getting exception

Please find the Apache POI java code to read the .xls file.
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
while reading the .xls file using Java Apache POI, I am getting the below error in the Java Console.
java.io.IOException: Invalid header signature; read 0x6C6D783F3CBFBBEF, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document
I am able to manually open the excel file without any issues. Do we have the solution to overcome this. I'm completely out of ideas so any help/pointers are greatly appreciated :)
FileInputStream fis = new FileInputStream(new File(yourpath+"/WebContent/ProductUpload.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook (fis);
int numberOfSheets = workbook.getNumberOfSheets();
for(int i=0; i < numberOfSheets; i++){
XSSFSheet sheet = workbook.getSheetAt(i);
Iterator ite = sheet.rowIterator();
while(ite.hasNext()){
Row row = (Row)ite.next();
Iterator<org.apache.poi.ss.usermodel.Cell> cite = row.cellIterator();
while(cite.hasNext()){
org.apache.poi.ss.usermodel.Cell cell = cite.next();
}
}
}

Appending sheet to existing excel file using Java and Apache POI

I have a Java method writeToExcel(String sheetName, Map), which creates a new sheet with name 'sheetName' in a new excel file and write the map data into it . When I call the method with different sheetName arguments more than once, existing sheet gets replaced by the last called one. I want to create new sheets in the same excel file each time whenever the method is called with different sheetName argument, without losing existing sheets. Here is my code.
public static void writeToExcel(String fileName,Map<Integer,String[]> excelData){
String filePath="/Data/excel.xlsx";
XSSFWorkbook workbook=new XSSFWorkbook();
XSSFSheet sheet=workbook.createSheet(fileName);
Set<Integer> keySet=excelData.keySet();
int passedCount=0;
int failedCount=0;
int rowNo=0;
int cellNo=0;
Row row;
Cell cell;
try{
File file=new File(filePath);
FileOutputStream output=new FileOutputStream(file);
for(Integer key:keySet){
row=sheet.createRow(rowNo++);
String[] dataToWrite=excelData.get(key);
cellNo=0;
for(String str:dataToWrite){
cell=row.createCell(cellNo++);
cell.setCellValue(str);
}
}
workbook.write(output);
output.close();
workbook.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
Seems like you're always creating a new workbook in the second line of the method. So it is not the sheet that is replaced but the entire workbook. Better use
XSSFWorkbook workbook=new XSSFWorkbook(new File(filePath));
That should do the trick.
XSSFWorkbook workbook=new XSSFWorkbook(new File(filePath)); => XSSFWorkbook workbook=new XSSFWorkbook(filePath); as no suit constructor for XSSFWorkbook workbook=new XSSFWorkbook(new File(filePath))

Java POI Create new Workbook with SS model?

I'm a little confused, I used to do this:
HSSFWorkbook wb = new HFFSWorkbook();
But with the new POI, I dont have to do that.
I can't do this:
Workbook wb = new Workbook();
I understand WorkbookFactory.create, but that is for opening a file.
How do I set up a new workbook with this ss model?
You can still use the SS model but need to decide on the file format at the time of creation.
For xls -> Workbook wb = new HSSFWorkbook();
For xlsx -> Workbook wb = new XSSFWorkbook();
In "New POI", you can write/read both XLS files and XLSX files. In any case, for XLS file-format you were using:
HSSFWorkbook wb = new HSSFWorkbook();
So for XLSX file-format, you have to use:
XSSFWorkbook wb = new XSSFWorkbook();
// you could also do below
// Workbook wb = new XSSFWorkbook();
Also it would be helpful for you if you refer below links for starting with XLS to XLSX migration.
1. http://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFWorkbook.html
2. http://poi.apache.org/spreadsheet/converting.html
Make sure you download and add the POI JAR file to your project’s class path before running the code. The Apache POI JAR file can be found here.
public void main(String[] args) throws IOException {
// Directory path where the xls file will be created
String destinationFilePath = "C:/Users/devesh_/Documents/HelloWorld.xls";
// Create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(destinationFilePath);
// Build the Excel File
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
HSSFWorkbook workBook = new HSSFWorkbook();
// Create the spreadsheet
HSSFSheet spreadSheet = workBook.createSheet("Hello_World");
// Create the first row
HSSFRow row = spreadSheet.createRow((short) 0);
// Create the cells and write to the file
HSSFCell cell;
// Write Hello
cell = row.createCell(0);
cell.setCellValue(new HSSFRichTextString("Hello"));
// Write World
cell = row.createCell(1);
cell.setCellValue(new HSSFRichTextString("World"));
workBook.write(outputStream);
outputStream.writeTo(fout);
outputStream.close();
fout.close();
}
When creating a file, you need to decide up front what format it'll be - you can't just wait until write-out time to do that. You code would be something like:
Workbook wb = null;
if (shouldBeXLS) {
wb = new HSSFWorkbook();
} else {
wb = new XSSFWorkbook();
}
// work on the file in a generic way
// save, with a suitable name
String filename = "test.xls";
if (!shouldBeXLS) { filename = filename + "x"; }
FileOutputStream fout = new FileOutputStream(filename);
wb.write(fout);
fout.close();
At the start, decide what format you want for this particular instance, and create that. Treat it as a general workbook, and write to it in the common way. At the end, remember what it is so you can give the file the right extension!
(When reading a file in, WorkbookFactory will let you load the appropriate instance for the file type. When creating a new file, you have to pick yourself as there's nothing there yet!)

Categories