Not able to write data in xlsx file using java? - 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

Related

Apache POI not "Saving" excel file

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

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

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

How to write multiple data via looping to excel (Jxl)

In my below code, I want to write multiple data to excel but it's writing only the first value and not the remaining.
I am trying to read from webpage and write it to a excel sheet. Below is set of code works fine, but i am not able to figure out how to run this in a loop. As i have to write many value which i am reading from the table
Could anybody sort this out.
String m1 = (driver.findElement(By.xpath(".//*[#id='dhfdshjfdsfdsf']")).getText());
System.out.println(m1);
WritableWorkbook wb = Workbook.createWorkbook(new File("D:\\output_2.xls"));
writableSheet ws = wb.createSheet("customsheet",1);
{
Label label = new Label(0,0,m1);
ws.addCell(label);
}
wb.write();
wb.close();
I have edited your code to write for multiple values. Check once with below code.
WritableWorkbook wb = Workbook.createWorkbook(new File("D:\\output_2.xls"));
writableSheet ws = wb.createSheet("customsheet",1);
int rowsize = ws.getRows();
int c=0;
//if m1 contains 20 values then it upadtes till 20 rows
for(int i=rowsize; i<rowsize+20; i++) {
String m1 = (driver.findElement(By.xpath(".//*[#id='dhfdshjfdsfdsf']")).getText());
System.out.println(m1);
Label label = new Label(c,i,m1);
ws.addCell(label);
}
wb.write();
wb.close();

Changing value of cell in Excel via apache-poi

I'm trying to change value of cell in .xls document.
In .xls file i have got only 1 cell - A1 with abc value inside.
My code:
File fo = new File("D:\\TMP\\Zeszyt1.xls");
HSSFWorkbook a = new HSSFWorkbook(new FileInputStream(fo));
HSSFSheet my_sheet = a.getSheetAt(0);
HSSFRow my_row = my_sheet.getRow(0);
HSSFCell myCell;
myCell = my_row.getCell(0);
myCell.setCellValue("NEW VALUE");
How to commit this changes? When i open .xls file i still have got abc value inside A1.
You have to write to the file.
FileOutputStream outputStream = new FileOutputStream(new File("abc.xls"));
workbook.write(outputStream);
outputStream.close();//Close in finally if possible

Categories