I want to generate Excel Report but I am not able to generate excel report , I don't know what is the problem ?
I need to generate automated report everytime I click on generate report button.
I am using sqlyog,my table name is final and my database name is etc. my database table entries are not static so I need an automated report .
I am using Eclipse IDE
Is it that I need to use any more external api.
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ExcelDatabase {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost/etc", "root", "");
Statement statement = connect.createStatement();
ResultSet resultSet = statement.executeQuery("select * from final");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet spreadsheet = workbook.createSheet("engine report");
HSSFRow row = spreadsheet.createRow(1);
HSSFCell cell;
cell = row.createCell(1);
cell.setCellValue("engine_code");
cell = row.createCell(2);
cell.setCellValue("var1");
cell = row.createCell(3);
cell.setCellValue("var2");
cell = row.createCell(4);
cell.setCellValue("var3");
cell = row.createCell(5);
cell.setCellValue("var4");
cell = row.createCell(6);
cell.setCellValue("var5");
cell = row.createCell(7);
cell.setCellValue("User_Name");
cell = row.createCell(8);
cell.setCellValue("time_stamp");
int i = 2;
while (resultSet.next()) {
row = spreadsheet.createRow(i);
cell = row.createCell(1);
cell.setCellValue(resultSet.getInt("ec"));
cell = row.createCell(2);
cell.setCellValue(resultSet.getString("v1"));
cell = row.createCell(3);
cell.setCellValue(resultSet.getString("v2"));
cell = row.createCell(4);
cell.setCellValue(resultSet.getString("v3"));
cell = row.createCell(5);
cell.setCellValue(resultSet.getString("v4"));
cell = row.createCell(6);
cell.setCellValue(resultSet.getString("v5"));
cell = row.createCell(7);
cell.setCellValue(resultSet.getString("user"));
cell = row.createCell(8);
cell.setCellValue(resultSet.getString("time"));
i++;
}
FileOutputStream out = new FileOutputStream(new File("exceldatabase.xls"));
workbook.write(out);
out.close();
System.out.println("exceldatabase.xls written successfully");
}
}
I created a same table in database as yours and tried running your code.
i could create Excel file without changing your code.
Just the difference is i used different driver ("oracle.jdbc.driver.OracleDriver"). So first check your database connection. If it is successful then rest of the code should work fine.
Please post the more specific exception if any.
That will help solve the problem.
One more thing you have used indexing from row 1 and cell 1 but POI uses indexing of rows and columns from 0.
Read Excel file and generate report as follows
You can read all rows and columns from excel and display it in your UI.
FileInputStream file = new FileInputStream("exceldatabase.xls");
Workbook wb = new HSSFWorkbook(file);
Sheet sheet = wb.getSheet("engine report");
int lastRowNum = sheet.getLastRowNum();
for(int rowIndex = 0 ; rowIndex < lastRowNum ; rowIndex++){
Row currRow = sheet.getRow(rowIndex);
if(currRow != null) {
List<String> currRowValues = new ArrayList<String>();
for(int cellNo = currRow.getFirstCellNum(); cellNo < currRow.getLastCellNum();cellNo++) {
Cell currCell = currRow.getCell(cellNo);
if(currCell != null) {
int cellType = currCell.getCellType();
switch(cellType) {
case Cell.CELL_TYPE_BLANK :
currRowValues.add("");
break;
case Cell.CELL_TYPE_BOOLEAN :
currRowValues.add(String.valueOf(currCell.getBooleanCellValue()));
break;
case Cell.CELL_TYPE_NUMERIC :
currRowValues.add(String.valueOf(currCell.getNumericCellValue()));
break;
case Cell.CELL_TYPE_STRING :
currRowValues.add(currCell.getStringCellValue());
break;
case Cell.CELL_TYPE_ERROR :
currRowValues.add("");
break;
}
} else {
currRowValues.add("");
}
}
// Add your code here
// Add current list to your UI or the way you want to display report
System.out.println( currRowValues);
}
}
For adding Header in Excel file use following code.
You should create a Merged region in sheet.
You can provide range be be merged using CellRangeAddress. Which takes startRow, endRow , startCol ,endCol as values to create cell range address.
After creating merged region you should set the value in left most cell in region i.e. cell at startRow,startCol.
I have used alignment to align content in center.
Save your file and you will get the expected result. :)
HSSFRow createRow = spreadsheet.createRow(0);
CellRangeAddress range = new CellRangeAddress(0, 0, 1, 8);
spreadsheet.addMergedRegion(range);
HSSFCell createCell = createRow.createCell(1);
createCell.setCellValue("My header");//ADD Your Custom Header value Here
CellUtil.setAlignment(createCell, workbook, CellStyle.ALIGN_CENTER);
You can create excel sheet via java code using apache poi library classes like HSSFSheet, HSSFRow.
import java.io.ByteArrayOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
public class CreateExcel(){
public static void main(String args[]){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheet 1");
HSSFRow row = sheet.createRow(rowNumber); // 0,1,2..
HSSFCell cell = row.createCell(columnNumber); // 0,1,2...
cell.setCellValue("Hello Apache POI !");
HSSFFont font = workbook.createFont();
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
cell.setCellStyle(style);
workbook.write(baos);
baos.flush();
}
}
Using above program you can create an excel sheet.
It seems you are overwriting the same row and cell objects again and again.
for each new cell you need to create a new object :
//instead of
HSSFCell cell;
cell = row.createCell(1);
cell.setCellValue("engine_code");
cell = row.createCell(2);
cell.setCellValue(resultSet.getString("v1"));
//do
HSSFCell cell1 = row.createCell(1);
cell1.setCellValue("engine_code");
HSSFCell cell2 = row.createCell(2);
cell2.setCellValue(resultSet.getString("v1"));
The same applies to rows objects:
HSSFRow row1 = spreadsheet.createRow(1);
HSSFRow row2 = spreadsheet.createRow(2);
Related
Hey all I am trying to get my cell to vertical line instead of just being aligned by the left side using POI.
This is my java code:
static CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle = workbook.createCellStyle();
Row headerRow = null;
sheet = workbook.createSheet("String " + sheetname);
headerCellStyle.setWrapText(true);
headerCellStyle.setAlignment(HorizontalAlignment.LEFT);
headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerCellStyle.setVerticalAlignment(VerticalAlignment.MIDDLE);
// Create a Row
headerRow = sheet.createRow(0);
However, the line headerCellStyle.setVerticalAlignment(VerticalAlignment.MIDDLE); has an error of:
The method setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment) in the type CellStyle is not applicable for the arguments (org.apache.poi.sl.usermodel.VerticalAlignment)
How can i go about getting this to work if I have already defined it as an static CellStyle headerCellStyle = workbook.createCellStyle();?
Changing to SS does not seem to have the "middle" option?
This is the difference within excel for those 2 types:
The default way:
The Middle way (the way I am wanting):
The Center way:
Your second image (the way you want) shows CellStyle.setVerticalAlignment(VerticalAlignment.CENTER). Your third image shows CellStyle.setAlignment(HorizontalAlignment.CENTER).
There is a difference between setVerticalAlignment(VerticalAlignment.CENTER) and setAlignment(HorizontalAlignment.CENTER). The first sets vertical alignment to center (aka middle). The second sets horizontal alignment to center.
Complete Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
class CreateExcelVerticalAlignment {
public static void main(String[] args) throws Exception {
// try (Workbook workbook = new XSSFWorkbook();
// FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {
try (Workbook workbook = new HSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("Excel.xls") ) {
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle = workbook.createCellStyle();
headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
Sheet sheet = workbook.createSheet();
sheet.setColumnWidth(0, 20*256);
Row row = sheet.createRow(0);
row.setHeightInPoints(40);
Cell cell = row.createCell(0);
cell.setCellStyle(headerCellStyle);
cell.setCellValue("1082192560 1868");
workbook.write(fileout);
}
}
}
Result:
Im having difficulty with using Apache POI API. Im trying to import an excel them only select certain rows and cells to extract from the import. Im currently able to import, but i cant extract certain cell. Here is code:
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import java.io.File;
import java.io.IOException;
public class ExcelReader {
public static final String path = "C:/Users/xxxx/Documents/import testing.xlsx";
public static void main(String[] args) throws IOException, InvalidFormatException {
// Create a workbook with data from excel file
Workbook workbook = WorkbookFactory.create(new File(path));
// Save sheets from workbook
Sheet sheet = workbook.getSheetAt(0);
// Make sure the data is saved in string format using a data formatter
DataFormatter dataFormatter = new DataFormatter();
// Iterate through cells and columns, printing their content
System.out.println("\n\nThe content of the excel file: " + path + "\n");
String cellContent;
for (Row row: sheet) {
for(Cell cell: row) {
cellContent = dataFormatter.formatCellValue(cell);
if(cellContent == null || cellContent.trim().isEmpty()){
// Give the empty cells the content "empty", to make it easy to filter out later on
cellContent = "empty";
}
System.out.print(cellContent + "\t");
}
CellReference cellReference = new CellReference("A11");
XSSFRow rowT = sheet.getRow(cellReference.getRow());
if (rowT != null) {
XSSFCell cell = rowT.getCell(cellReference.getCol());
}
System.out.println();
}
// Close the connection to the workbook
workbook.close();
}
}
Changing Workbook to XSSFWorkbook and Sheet to XSSFSheet seems to fix the compilation issue.
XSSFWorkbook workbook = new XSSFWorkbook(new File(path));
and
XSSFSheet sheet = workbook.getSheetAt(0);
try with this for get "A11" cell
XSSFCell cell = sheet.getRow(10).getCell(0); // 10 = id of the 11th row, 0 = id of the 1st (A) column
or
XSSFCell cell = sheet.getRow(10).getCell(CellReference.convertColStringToIndex("A"));
create cell reference for B12
CellReference cr = new CellReference("B12");
row = mySheet.getRow(cr.getRow());
cell = row.getCell(cr.getCol());
I use Apache POI 3.16 to create an Excel file. I want to set the data inside a particular cell to have a linebreak :
rowConsommationEtRealisation.createCell(0).setCellValue("Consommation (crédits)\r\nRéalisation (produits)");
When I open the file then the cell value does not have linebreak ! So how to create linebreak ?
Try this: here
Row row = sheet.createRow(2);
Cell cell = row.createCell(2);
cell.setCellValue("Use \n with word wrap on to create a new line");
//to enable newlines you need set a cell styles with wrap=true
CellStyle cs = wb.createCellStyle();
cs.setWrapText(true);
cell.setCellStyle(cs);
It has the line break already but the cell does not show it. You need setting a cell style having wrap text property set to the cell.
Example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
class ExcelLineBreakWrapText {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
CellStyle wrapStyle = workbook.createCellStyle();
wrapStyle.setWrapText(true);
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(wrapStyle);
cell.setCellValue("Consommation (crédits)\r\nRéalisation (produits)");
sheet.autoSizeColumn(0);
workbook.write(new FileOutputStream("ExcelLineBreakWrapText.xlsx"));
workbook.close();
}
}
Following is my code:
String monthEndDate = "31-Dec-17";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy",java.util.Locale.ENGLISH);
XSSFCell updateDateCell = sheet.getRow(rownumber).getCell(15);
XSSFCellStyle cellStyle = (XSSFCellStyle)updateDateCell.getCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("dd-MMM-yy"));
Date updateDate = sdf.parse(monthEndDate);
updateDateCell.setCellValue(updateDate);
updateDateCell.setCellStyle(cellStyle);
It is setting numeric value 43100.0
I suspect your problem is that you are getting the CellStyle via Cell.getCellStyle and then you are overwriting that CellStyle.
CellStyles are in Excel defined on Workbook level. That means, not each cell has it's own cell style but cells share cell styles defined on workbook level.
So if you do the getting the CellStyle via Cell.getCellStyle and then overwriting that CellStyle multiple times then only the last overwriting will be active. So I suspect, your complete code overwrites the same cell style, gotten from another cell, with another number format after you have overwritten it with the date number format.
The easy conclusion could be to really give each cell it's own cell style. But this is also wrong since there is a limit number of cell styles in a workbook. So we need
Having as much own cell styles as needed.
Having as much cell styles shared as possible.
To achieve this CellUtil can be used in apache poi. This provides methods only to create a new cell style if there is not already the same cell style defined in the workbook and simply to use that cell style if there is already the same cell style defined in the workbook.
Example:
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
public class ExcelSetDateValue {
public static void main(String[] args) throws Exception {
XSSFWorkbook wb = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("ExcelTest.xlsx"));
//possiby we need data formats
DataFormat dataFormat = wb.createDataFormat();
//get sheet and set row number
XSSFSheet sheet = wb.getSheetAt(0);
int rownumber = 3;
//get the date
String monthEndDate = "31-Dec-17";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy", java.util.Locale.ENGLISH);
Date updateDate = sdf.parse(monthEndDate);
//set date as cell value
XSSFCell updateDateCell = sheet.getRow(rownumber).getCell(15);
updateDateCell.setCellValue(updateDate);
//use CellUtil to set the CellStyleProperties
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(CellUtil.DATA_FORMAT, dataFormat.getFormat("dd-MMM-yy"));
CellUtil.setCellStyleProperties(updateDateCell, properties);
wb.write(new FileOutputStream("ExcelTestNew.xlsx"));
wb.close();
}
}
Add updateDateCell = Format(updateDateCell, "dd-MMM-yyyy") at the end of your code.
You should get 31-Dec-2017.
This is an example which I already have for formatting date, you can reuse the part of it ( I marked the relevant lines of code). It's tested and working fine, if any issue let me know.
//UPDATE
Please see Axel Richter's answer https://stackoverflow.com/a/47920182/1053496 for the correct answer. In my example, I'm storing date as String instead of Date object which is not the recommended way
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.xssf.usermodel.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteExcelBasic {
public static void main(String[] args) throws IOException {
String excelFileName = "/Users/home/Test3.xls";
FileOutputStream fos = new FileOutputStream(excelFileName);
XSSFWorkbook wb = new XSSFWorkbook();
XSSFCellStyle style = wb.createCellStyle();
XSSFSheet sheet = wb.createSheet("sheet");
XSSFFont urlFont = wb.createFont();
style.setFont(urlFont);
String monthEndDate = "31-Dec-17";
DataFormat df = wb.createDataFormat(); //these 3 lines are enough
short dateFormat = df.getFormat("dd-MMM-yy"); // 2nd
style.setDataFormat(dateFormat); // 3rd
for (int r = 0; r < 1; r++) {
XSSFRow row = sheet.createRow(r);
row.setHeight((short) -1);
for (int c = 0; c < 3; c++) {
XSSFCell cell = row.createCell(c);
String ss = "31-Dec-17";
cell.setCellValue(ss);
style.setWrapText(true);
cell.setCellStyle(style);
}
}
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
wb.write(baos);
byte[] myByteArray = baos.toByteArray();
fos.write(myByteArray);
fos.flush();
}
finally {
wb.close();
fos.close();
}
}
}
I'm trying to get updated cell values after use setForceFormulaRecal method. But I'm getting still old values. Which is not actual result. If I opened Original file by clicking It will asking update Links dialogue box. If I click "ok" button then Its updating all cell formula result. So I want to update excel sheet links before its open by using poi. Please help in this situation.
//Before Setting values
HSSFCell cel2=row1.getCell(2);
HSSFCell cel4=row1.getCell(5);
cel2.setCellValue(690);
cel4.setCellValue(690);
wb.setForceFormulaRecalculation(true);
wb.write(stream);
//After Evaluatting the work book formulas I'm trying as follow
HSSFWorkbook wb = HSSFReadWrite.readFile("D://workspace//ExcelProject//other.xls");
HSSFSheet sheet=wb.getSheetAt(14);
HSSFRow row11=sheet.getRow(10);
System.out.println("** cell val: "+row11.getCell(3).getNumericCellValue());
I'm Also tried with Formula Evaluator But its showing errors As follow
Could not resolve external workbook name '\Users\asus\Downloads\??? & ???? ?????_091230.xls'. Workbook environment has not been set up.
at org.apache.poi.ss.formula.OperationEvaluationContext.createExternSheetRefEvaluator(OperationEvaluationContext.java:87)
at org.apache.poi.ss.formula.OperationEvaluationContext.getArea3DEval(OperationEvaluationContext.java:273)
at org.apache.poi.ss.formula.WorkbookEvaluator.getEvalForPtg(WorkbookEvaluator.java:660)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateFormula(WorkbookEvaluator.java:527)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:288)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluate(WorkbookEvaluator.java:230)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCellValue(HSSFFormulaEvaluator.java:351)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCell(HSSFFormulaEvaluator.java:213)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateAllFormulaCells(HSSFFormulaEvaluator.java:324)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateAll(HSSFFormulaEvaluator.java:343)
at HSSFReadWrite.readSheetData(HSSFReadWrite.java:85)
at HSSFReadWrite.main(HSSFReadWrite.java:346)
Caused by: org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment$WorkbookNotFoundException: Could not resolve external workbook name '\Users\asus\Downloads\??? & ???? ?????_091230.xls'. Workbook environment has not been set up.
at org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment.getWorkbookEvaluator(CollaboratingWorkbooksEnvironment.java:161)
at org.apache.poi.ss.formula.WorkbookEvaluator.getOtherWorkbookEvaluator(WorkbookEvaluator.java:181)
at org.apache.poi.ss.formula.OperationEvaluationContext.createExternSheetRefEvaluator(OperationEvaluationContext.java:85)
... 11 more
OK, trying an answer:
First of all: Support for links to external workbooks is not included into the current stable version 3.10. So with this version it is not possible to evaluate such links directly. That's why evaluateAll() will fail for workbooks with links to external workbooks.
With Version 3.11 it will be possible to do so. But also only even if all the workbooks are opened and Evaluators for all the workbooks are present. See: http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/FormulaEvaluator.html#setupReferencedWorkbooks%28java.util.Map%29
What we can do with the stable version 3.10, is to evaluate all the cells which contains formulas which have not links to external workbooks.
Example:
The workbook "workbook.xlsx" contains a formula with a link to an external workbook in A2:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;
import java.util.HashMap;
class ExternalReferenceTest {
public static void main(String[] args) {
try {
InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0);
if (row == null) row = sheet.createRow(0);
Cell cell = row.getCell(0);
if (cell == null) cell = row.createCell(0);
cell.setCellValue(123.45);
cell = row.getCell(1);
if (cell == null) cell = row.createCell(1);
cell.setCellValue(678.90);
cell = row.getCell(2);
if (cell == null) cell = row.createCell(2);
cell.setCellFormula("A1+B1");
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
//evaluator.evaluateAll(); //will not work because external workbook for formula in A2 is not accessable
System.out.println(sheet.getRow(1).getCell(0)); //[1]Sheet1!$A$1
//but we surely can evaluate single cells:
cell = wb.getSheetAt(0).getRow(0).getCell(2);
System.out.println(evaluator.evaluate(cell).getNumberValue()); //802.35
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (InvalidFormatException ifex) {
} catch (FileNotFoundException fnfex) {
} catch (IOException ioex) {
}
}
}