Apache POI not "Saving" excel file - java

I am writing a small utility that creates a pivot table in an excel sheet using POI and I want to read the data from the pivot table back to the program which will save it as a PDF file using Itext. I am running into a problem where the program cannot read the data from the pivot table after it is created. The program only can "see" the information in the pivot table after I manually open the created file and hit the save button in excel. Does anyone know a way to read the data from the pivot table from the XSSFPivotTable object or otherwise force a way for the file to "save" so it can be accessed by the program again?
Here is a snippet of code so you can see what I'm talking about. I'm a student so any advice on best practices would be greatly appreciated as well.
public void returnPivotData() throws IOException {
FileInputStream fs = new FileInputStream(this.xlsxFile);
XSSFWorkbook book = new XSSFWorkbook(fs);
XSSFSheet dataSheet = book.getSheet("Sheet1");
AreaReference dataRef = new AreaReference("A1:E15",
SpreadsheetVersion.EXCEL2007);
XSSFPivotTable table = dataSheet.createPivotTable(dataRef,
new CellReference("A16"));
table.addRowLabel(0);
table.addColumnLabel(DataConsolidateFunction.SUM, 3);
// Save the data back to the file
FileOutputStream fsOut = new FileOutputStream(
"D:\\workspace\\test.xlsx");
book.write(fsOut);
fsOut.close();
book.close();
fs.close();
// This does not allow access
FileInputStream fsIn = new FileInputStream("D:\\workspace\\test.xlsx");
XSSFWorkbook bookNew = new XSSFWorkbook(fsIn);
XSSFSheet sheet = bookNew.getSheet("Sheet1");
for (int i = 0; i < 20; i++) {
XSSFRow rowNew = sheet.getRow(i);
XSSFCell cellNew = rowNew.getCell(0,
MissingCellPolicy.CREATE_NULL_AS_BLANK);
System.out.println(cellNew.toString());
}
fsIn.close();
bookNew.close();
}

Related

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

Cannot read files written using SXSSFWorkbook in java

I want to read and write large excel files. Therefore, I used SXSSFWorkbook to write the excel file and XSSF and SAX EVENT API to read the files.
However, the cell content is empty when the excel file is read, and if the excel file is written using SXSSFWOrkbook. If I open the written excel file and save it again, the content is shown correctly.
The following is the code I used to write the excel file.
SXSSFWorkbook wb = new SXSSFWorkbook();
wb.setCompressTempFiles(true);
SXSSFSheet sh = (SXSSFSheet) wb.createSheet();
// sh.setRandomAccessWindowSize(100);// keep 100 rows in memory,
// exceeding rows will be flushed to disk
for (int rownum = 0; rownum < 100; rownum++) {
Row row = sh.createRow(rownum);
for (int cellnum = 0; cellnum < 10; cellnum++) {
Cell cell = row.createCell(cellnum);
String address = new CellReference(cell).formatAsString();
cell.setCellValue(address);
}
}
FileOutputStream out = new FileOutputStream("D:\\tempsxssf.xlsx");
wb.write(out);
out.flush();
out.close();
wb.dispose();
I am in a big trouble, can someone help me to figure out the issue?
I used another constructor according POI documentation
SXSSFWorkbook(workbook, rowAccessWindowSize, compressTmpFiles, useSharedStringsTable)
Like this:
SXSSFWorkbook workbook = new SXSSFWorkbook(null, 1000, true, true);
where you can enable shared strings table

How to clear contents of a column in excel sheet using java

I want to clear contents of 3 columns in excel sheet(.xlsx file) using java before execution of my selenium script. i am using XSSFWorkbook(Apache poi) for read and write data to excel sheet.There are 5 columns in excel sheet.I want to clear 3 column contents and remaining column content should keep like before.
please help me how can i achieve that?
FileInputStream objFileInputStream = new FileInputStream(new File(
Xlsx_File_path.xlsx));
XSSFWorkbook objWorkbook = new XSSFWorkbook(objFileInputStream);
XSSFSheet objSheet = objWorkbook.getSheetAt(0);
Cell cell = null;
int row=[start of row]
int cell=[your cell]
//iterate the below code as you want
//code
cell = objSheet.getRow(rows).getCell(cell);
cell.setCellValue("")
//code
objFileInputStream.close();
FileOutputStream output_file = new FileOutputStream(new File(
finalXlsx.xlsx));
objWorkbook.write(output_file);
output_file.close();

Java write csv-String to Excel

in my program i want to write an String to *.xlsx
Example for the String:
a,b,c,d,e,,f,\na,b,c,d,e,,f,\n
I want to write an Excel file which looks like this:
How can I do this?
private void createExcel() throws Exception {
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet = workbook.createSheet("Excel Sheet");
How can I create the rows and columns from my csvString?
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("FilePath.xlsx"));
workbook.write(out);
out.close();
System.out.println("*.xlsx written successfully" );
}
I'm thankful for any help
Using XSSFSheet.createRow(), you can create rows as required.
In your case, you would have to split the string by ,\n and make a XSSFSheet.createRow() call for each element of the resulting array.
Using XSSFRow.createCell(), you can create cells, for which a split by , would be required. To set the value, Cell.setCellValue() has to be invoked with each comma separated part.
Simple example here.
private void createExcel() throws Exception {
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet_1 = workbook.createSheet("Excel Sheet");
ArrayList<String> arrRows = new ArrayList<String>(Arrays.asList(Text.split("\n")));
for (int i = 0; i < arrRows.size(); i++) {
XSSFRow row = spreadsheet_1.createRow(i);
ArrayList<String> arrElement = new ArrayList<String>(Arrays.asList(arrRows.get(i).split(",")));
for(int j = 0; j < arrElement.size(); j++) {
XSSFCell cell = row.createCell(j);
cell.setCellValue(arrElement.get(j));
}
}
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("FilePath.xlsx"));
workbook.write(out);
out.close();
System.out.println("*.xlsx written successfully" );
}
Like #Naveed S said first I split my Text at every \N and create a Row for each element. Then I Split the elements at ,and create Cells
Thanks for the help and suggestion it really helped me

Read and write data to excel using POI - It deletes my original data from excel after write new data

I am first reading data from excel and then write in same excel. It works fine first time. Just after data written , It deletes my original data which was there from very beginning.
code is given below :
public static void main (String args[]) throws Exception {
//CODE TO REMOVE UNNECESSARY WARNING
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
//CALL FIREFOX DRIVER TO OPEN IT
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/?gfe_rd=cr&ei=VQiAVOeCFavM8gf59IHACg&gws_rd=ssl#q=software+testing");
java.util.List<WebElement> links = driver.findElements(By.tagName("h3"));
int sizecount = links.size();
System.out.println(sizecount);
FileInputStream input = new FileInputStream("D:\\sel.xls");
int count=0;
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sh = wb.getSheet("sheet1");
HSSFRow row = sh.getRow(count);
String data = row.getCell(0).toString();
System.out.println(data);
FileOutputStream webdata = new FileOutputStream ("D:\\sel.xls");
int inc = 1;
for(int i=1;i<=links.size()-1;i++)
{
HSSFRow row1 = sh.createRow(count);
row1.createCell(inc).setCellValue(links.get(i).getText());
count++;
}
wb.write(webdata);
if you are updating it, you should also update the count variable with the last line of the excel
int inc = 1;
count = sh.getPhysicalNumberOfRows();
and do the rest...
you are facing the issue because the index of excel sheets are same when you are writing.
First you should check wheater the cell is empty or not then you should write.
Or you can first do getrows() or getcolumn() it will give you the size of the rows and columns.
once you have the size you can write your data after the that row size and column.

Categories