exporting tables to excel / word using POI - java

I want the code to export tables / reports to Excel and Word using POI.
I saw the examples that came with POI but could not understand. Can anyone provide me a small/easy code to do the same.

Seeing as you wanted actual code for using POI. Here is some to do some exporting:
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.StringTokenizer;
import java.io.*;
import org.apache.poi.hssf.usermodel.*;
public class XLSExporter implements Exporter {
/**
* Constructor for XLSExporter
*/
public XLSExporter(){
}
public void exportFile( File f, List o ) throws IOException{
HSSFWorkbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream(f);
HSSFSheet sheet = wb.createSheet();
ListIterator it = o.listIterator();
//Construct the headings
HSSFRow headingsRow = sheet.createRow((short)0);
//Heading format
HSSFFont headingFont = wb.createFont();
headingFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle headingStyle = wb.createCellStyle();
headingStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headingStyle.setFont(headingFont);
HSSFCell headingA = headingsRow.createCell((short)0);
headingA.setCellValue("Heading");
headingA.setCellStyle(headingStyle);
int i = 1;
// Iterate over the rows
while(it.hasNext()){
//Create the row
HSSFRow row = sheet.createRow((short)i);
//Write data
HSSFCell cellRunway = row.createCell((short)0);
cellRunway.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cellRunway.setCellValue("Whateva");
cellRunway.setCellStyle(standardStyle);
i++;
}
//Set the column widths where needed
sheet.setColumnWidth((short)1, (short)4000);
wb.write(fileOut); // Write the workbook
fileOut.close();
}
}

Related

Excel Apache POI is printing only last element while performing setCellValue()

I am reading some data from excel and writing it to another sheet in the same file in the form of column and I want the column to be printed in the row. When I am performing iteration createRow().setCellValue() is printing only last element.
package com.editDistance;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadColumnsEditDistance {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File src = new File("C:\\Users\\xyz\\Desktop\\folder\\file.xlsx");
FileInputStream file = new FileInputStream(src);
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet1 = workbook.getSheetAt(0);
int rows = sheet1.getPhysicalNumberOfRows();
workbook.createSheet();
Sheet sheet2 = workbook.getSheetAt(1);
for (int Readingrowindex = 1; Readingrowindex < rows; Readingrowindex++) {
String ah = sheet1.getRow(Readingrowindex).getCell(1).getStringCellValue();
sheet2.createRow(Readingrowindex).createCell(0).setCellValue(ah);
sheet2.createRow(0).createCell(Readingrowindex).setCellValue(ah);
}
FileOutputStream fout = new FileOutputStream(src);
workbook.write(fout);
}
}
Do you want to create sheet with the same cells in first column and first row, like a named table? If yes, you need modify your code, because you always rewrite first row, that's why you get only last item. Do this:
File src = new File("C:\\Users\\xyz\\Desktop\\folder\\file.xlsx");
FileInputStream file = new FileInputStream(src);
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet1 = workbook.getSheetAt(0);
int rows = sheet1.getPhysicalNumberOfRows();
workbook.createSheet();
Sheet sheet2 = workbook.getSheetAt(1);
Row sheet2FirstRow = sheet2.createRow(0);
for (int Readingrowindex = 1; Readingrowindex < rows; Readingrowindex++) {
String ah = sheet1.getRow(Readingrowindex).getCell(1).getStringCellValue();
sheet2.createRow(Readingrowindex).createCell(0).setCellValue(ah);
Cell cell = sheet2FirstRow.createCell(Readingrowindex);
cell.setCellValue((String) ah);
}
FileOutputStream fout = new FileOutputStream(src);
workbook.write(fout);
I think it's because you keep creating row 0 over and over again so it's overwriting what you already created.
You probably want to do something like this:
if(sheet2.getRow() == null){
sheet2.createRow(0).createCell(Readingrowindex).setCellValue(ah);
}else{
sheet2.getRow(0).createCell(Readingrowindex).setCellValue(ah);
}
I faced the similar problem while writing to the code (it was printing the last row only).
Here is the solution for my code:
Failed solution (printing only last cell) i.e. "Hello3"
sheet.createRow(8).createCell(0).setCellValue("Hello1");
sheet.createRow(8).createCell(1).setCellValue("Hello2");
sheet.createRow(8).createCell(2).setCellValue("Hello3");
Working solution (Printing all the data) :
XSSFRow row;
row = sheet.createRow(8);
row.createCell(0).setCellValue("India 123");
row.createCell(1).setCellValue("India 234");
row.createCell(2).setCellValue("India 3453");
row = sheet.createRow(9);
row.createCell(0).setCellValue("Test 123");
row.createCell(1).setCellValue("Test 234");
row.createCell(2).setCellValue("Test 3453");

POI Excel Selenium Decimal to text

I have data in Excel but when I run the code output in decimal but my excel cell format in Text
1.23456789E8
28.5
Also, how do I select radio button base on test data from excel sheet means select female button if cell data is female.
Also how to select data from the drop-down menu.
Attached image with Link for Excel file
//ReadExcelShe
package excelpoi;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelShe {
public Sheet readExcel(String filePath,String fileName,String sheetName) throws IOException {
//Create a object of File class to open xlsx file
File file = new File(filePath+"\\"+fileName);
//Create an object of FileInputStream class to read excel file
FileInputStream inputStream = new FileInputStream(file);
Workbook wb = new XSSFWorkbook(inputStream);
Sheet she = wb.getSheet(sheetName);
return she;
}
}
// googletestppo
package testpoi;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import excelpoi.ReadExcelShe;
public class googletestppo {
// TODO Auto-generated method stub
WebDriver driver;
#Test(dataProvider = "testdata")
public void login(String firstn, String lastn, String usern, String passw, String regusern, String password, String month, String day, String year) throws InterruptedException {
driver = new ChromeDriver();
driver.get("http://facebook.com/");
driver.findElement(By.name("firstname")).sendKeys(firstn);
///amidfdsds
driver.findElement(By.name("firstname")).sendKeys(lastn);
///sfasfasbad
driver.findElement(By.name("reg_email__")).sendKeys(usern);
//dsasfzxv#gmail.com
driver.findElement(By.name("reg_email_confirmation__")).sendKeys(regusern);
//dsasfzxv#gmail.com
driver.findElement(By.name("reg_passwd__")).sendKeys(password);
//1234567890 // this output come in decimal
WebElement maleRadioBtn = driver.findElement(By.id("u_0_a"));
maleRadioBtn.click();
WebElement femaleRadioBtn = driver.findElement(By.id("u_0_9"));
femaleRadioBtn.click();
Select dropdown = new Select(driver.findElement(By.id("month")));
dropdown.selectByVisibleText(month);
//Oct
Select dropdown1 = new Select(driver.findElement(By.id("day")));
dropdown1.selectByVisibleText(day);
//29 this come in decimal
Select dropdown2 = new Select(driver.findElement(By.id("year")));
dropdown2.selectByVisibleText(year);
// 1985 this come in decimal
driver.findElement(By.name("websubmit")).click();
}
#DataProvider(name = "testdata")
public String[][] readExcel() throws IOException {
ReadExcelShe file = new ReadExcelShe();
org.apache.poi.ss.usermodel.Sheet she = file.readExcel(System.getProperty("user.dir") + "\\", "DDF.xlsx", "Sheet2");
int rowCount = she.getLastRowNum();
int columnCount = she.getRow(0).getPhysicalNumberOfCells();
String[][] inputdata = new String[rowCount][columnCount];
for (int i = 0; i < rowCount; i++) {
Row row = she.getRow(i + 1);
for (int j = 0; j < columnCount; j++) {
inputdata[i][j] = row.getCell(j).toString();
System.out.println(inputdata[i][j]);
}
}
return inputdata;
}
}
I have data in Excel but when I run the code output in decimal but my excel cell format in >Text
1.23456789E8
28.5
See following post Always show two decimal points in excel cells using Apache poi
and official document: Busy Developers' Guide to HSSF and XSSF Features
You can indicate decimal format with DataFormat class. If you want to specify decimal format, then input set format as "#,##0.0000". Else please input format as "text".
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("format sheet");
CellStyle style;
DataFormat format = wb.createDataFormat();
Row row;
Cell cell;
int rowNum = 0;
int colNum = 0;
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(11111.25);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("0.0"));
cell.setCellStyle(style);
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(11111.25);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("#,##0.0000"));
cell.setCellStyle(style);
try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
wb.write(fileOut);
}
wb.close();
For Excel drop down list, see the post Excel Drop down list using Apache POI

Apache POI sets Values in Cells of an xlsx file, but doesnt confirm them in the processing strip

I'm trying to write values into a xlsx file using java and POI.
It's nearly working as I want, but i have the following Problem:
The Values that my programm writes into the xlsx file are displayed there, but excel doesn't use my VLOOKUP and displays #N/A untill I go into the
processing strip and press Enter, then it works..
Here is my code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
public class XLSXEditor {
public XLSXEditor(){
}
public void xlsxWriter(String path, String uName, Date date/*, String timeF, String timeT*/) throws FileNotFoundException, IOException{
File excel = new File(path);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(1);
int r = getNonBlankRowCount(path);
XSSFRow row = sheet.getRow(r);
//Datum Style
CellStyle csDate = book.createCellStyle();
CreationHelper createHelper = book.getCreationHelper();
csDate.setDataFormat(createHelper.createDataFormat().getFormat("dd.mm.yyyy"));
csDate.setBorderBottom(XSSFCellStyle.BORDER_THIN);
csDate.setBorderTop(XSSFCellStyle.BORDER_THIN);
csDate.setBorderLeft(XSSFCellStyle.BORDER_THIN);
csDate.setBorderRight(XSSFCellStyle.BORDER_THIN);
csDate.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());
csDate.setFillPattern(CellStyle.SOLID_FOREGROUND);
//uname style
CellStyle csUname = book.createCellStyle();
csUname.setBorderBottom(XSSFCellStyle.BORDER_THIN);
csUname.setBorderTop(XSSFCellStyle.BORDER_THIN);
csUname.setBorderLeft(XSSFCellStyle.BORDER_THIN);
csUname.setBorderRight(XSSFCellStyle.BORDER_THIN);
csUname.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());
csUname.setFillPattern(CellStyle.SOLID_FOREGROUND);
//fill username column in xlsx file
XSSFCell celluName = row.getCell(0, Row.RETURN_BLANK_AS_NULL);
while(celluName != null){
r++;
row = sheet.createRow(r);
celluName = row.createCell(0);
}
if(celluName == null){
celluName = sheet.getRow(r).createCell(0);
celluName.setCellStyle(csUname);
}
celluName.setCellValue(uName);
//fill date column in xlsx file
XSSFCell cellDate = row.getCell(5, Row.RETURN_BLANK_AS_NULL);
while(cellDate != null){
r++;
row = sheet.createRow(r);
cellDate = row.getCell(5);
}
if(cellDate == null){
cellDate = sheet.getRow(r).createCell(5);
cellDate.setCellValue(date);
cellDate.setCellStyle(csDate);
}
//fill PNr column in xlsx file
int r1 = r+1;
XSSFCell cellPNr = row.getCell(1, Row.RETURN_BLANK_AS_NULL);
cellPNr = sheet.getRow(r).createCell(1);
cellPNr.setCellValue("=SVERWEIS(A"+r1+";'MA Stamm'!$A$2:$E$98;2;FALSCH)");
FileOutputStream fos = new FileOutputStream(path);
book.write(fos);
fos.flush();
fos.close();
}
public int getNonBlankRowCount(String path) throws IOException{
File excel = new File(path);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(1);
int rowCount = 0;
int index = book.getSheetIndex(sheet);
if(index==-1){
rowCount=-1;
return rowCount;
}
else{
sheet=book.getSheetAt(index);
Iterator<Row> rowIterator = sheet.rowIterator();
rowCount=0;
while(rowIterator.hasNext()){
Row row = (Row) rowIterator.next();
XSSFCell cell =(XSSFCell) row.getCell(0, Row.RETURN_BLANK_AS_NULL);
if(cell == null){
break;
}
rowCount++;
}
return rowCount;
}
}
}
Formula cell content is fundamentally different from text cell content in Excel. Your code line:
cellPNr.setCellValue("=SVERWEIS(A"+r1+";'MA Stamm'!$A$2:$E$98;2;FALSCH)");
sets a string cell value instead of a formula. Do using Cell.setCellFormula instead to set formula cell content.
And since Excel stores only formulas in English_US notation in its files you need using English_US notation of the formula:
cellPNr.setCellFormula("VLOOKUP(A"+r1+",'MA Stamm'!$A$2:$E$98,2,FALSE)");
English_US notation means English function names (for ex. VLOOKUP instead of SVERWEIS), English constant names (for ex. FALSE instead of FALSCH), comma as parameter delimiter (for ex. VLOOKUP(A1,F1:G100,2,FALSE) instead of VLOOKUP(A1;F1:G100;2;FALSE)) and dot as decimal delimiter in floating point literals (for ex. SUM(1.23, 3.45, 4) instead of SUMME(1,23; 3,45; 4).
The localization is made in the localized Excel GUI versions after opening the file.
And then you need some kind of Formula Recalculation. Simplest way is by delegating re-calculation to Excel by setting:
book.setForceFormulaRecalculation(true);
before writing out the book.

Locking some Excel Cells/Rows with POI others editable

I have to write an excel File where some rows and Columns are locked and the rest is editable. I know this was asked and answered beofre, but the latest answer is from 2012 and the solution given there doesn't work anymore. Can anyone who worked with this give a solution that works now?
This is the code that was given as solution
String file = "c:\\poitest.xlsx";
FileOutputStream outputStream = new FileOutputStream(file);
Workbook wb = new XSSFWorkbook();
CellStyle unlockedCellStyle = wb.createCellStyle();
unlockedCellStyle.setLocked(false);
Sheet sheet = wb.createSheet();
sheet.protectSheet("password");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("TEST");
cell.setCellStyle(unlockedCellStyle);
wb.write(outputStream);
outputStream.close();
The effect now is a sheet that is locked completely.
You wrote, you'd like to lock certain cells and the default should be unlocked, but your code actually unlocks a given cell.
So I go for your original request and have kind of a quick hack as I haven't found a decent method on a quick view to set a whole range of columns:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;
public class XSSFLockTest {
public static void main(String args[]) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
CellStyle unlockedCellStyle = wb.createCellStyle();
unlockedCellStyle.setLocked(false);
CellStyle lockedCellStyle = wb.createCellStyle();
lockedCellStyle.setLocked(true);
XSSFSheet sheet = wb.createSheet();
CTCol col = sheet.getCTWorksheet().getColsArray(0).addNewCol();
col.setMin(1);
col.setMax(16384);
col.setWidth(9.15);
col.setStyle(unlockedCellStyle.getIndex());
sheet.protectSheet("password");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("TEST");
cell.setCellStyle(lockedCellStyle);
FileOutputStream outputStream = new FileOutputStream("bla.xlsx");
wb.write(outputStream);
outputStream.close();
}
}

POI Java - Numeric Cell with Decimals

I'm having a lot of problems with numeric formats in a Cell with POI.
I need to print in the cell 11 decimals for a number and also that the cell has a numeric format to make the sum when you select the data
And I have this code:
private void writeDecimal(HSSFRow row, Double data, int position) {
String pattern = "#.0000000000";
HSSFCell celda = row.createCell(position);
CellStyle styleDecimal = styles.get(ITEM_DECIMAL); // Font and alignment
styleDecimal.setDataFormat(libro.getCreationHelper().createDataFormat().getFormat(pattern));
celda.setCellStyle(styleDecimal);
celda.setCellType(Cell.CELL_TYPE_NUMERIC);
celda.setCellValue(data);
}
But the result always print less decimal because Excel rounds the number:
If I convert the Double to String, prints the 11 decimals but it doesn't make the sum if I select all the numbers.
Any idea how to resolve this?
Thanks
Open the xlsx file select the column , right click on cell -> Format cells...->custom->type = 0.00000000000 click ok.
now whatever you will write on that cell, it will print on that format and if you select also it will show the sum.
by code
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class ChangeXlxsDataFormat {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Workbook wb = new HSSFWorkbook();
Sheet sheet = (Sheet) wb.createSheet("format sheet");
CellStyle style;
DataFormat format = wb.createDataFormat();
Row row;
Cell cell;
short rowNum = 0;
short colNum = 0;
row = sheet.createRow(rowNum);
cell = row.createCell(colNum);
style = wb.createCellStyle();
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("0.00000000000"));
cell.setCellStyle(style);
cell.setCellValue(5.12345678908);
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(2.12345678908);
FileOutputStream fileOut = new FileOutputStream("test.xls");
wb.write(fileOut);
fileOut.close();
}
}
This code snippet doesn't contain celda.setCellStyle( styleDecimal ). Is it missing in the real code too? Add it.
Edit:
Here is a simple example using your function. It works well.
private static HSSFWorkbook workbook;
public static void main( String args[] ) throws IOException {
workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet( "sheet" );
HSSFRow row = sheet.createRow( 0 );
writeDecimal( row, 0.0781013, 0 );
FileOutputStream fos = new FileOutputStream( "workbook.xls", false );
workbook.write( fos );
fos.close();
}
private static void writeDecimal( HSSFRow row, Double data, int position ) {
String pattern = "#.0000000000";
HSSFCell celda = row.createCell(position);
CellStyle styleDecimal = workbook.createCellStyle(); // Font and alignment
styleDecimal.setDataFormat(workbook.createDataFormat().getFormat(pattern));
celda.setCellStyle(styleDecimal);
celda.setCellType(Cell.CELL_TYPE_NUMERIC);
celda.setCellValue(data);
}
What was the problem in your code? I don't know. Your style definitely wasn't applied to the page: zeros shouldn't be rendered with "#".

Categories