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());
Related
package demo;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Readwrite {
public static void main(String[] args) throws Exception
{
//Get the excel file and create an input stream for excel
FileInputStream fis = new FileInputStream("D:\\Testing_Team\\Age_Validation.xlsx");
//load the input stream to a workbook object
//Use XSSF for (.xlsx) excel file and HSSF for (.xls) excel file
XSSFWorkbook wb = new XSSFWorkbook(fis);
//get the sheet from the workbook by index
XSSFSheet sheet = wb.getSheet("Age");
//Count the total number of rows present in the sheet
int rowcount = sheet.getLastRowNum();
System.out.println(" Total number of rows present in the sheet : "+rowcount);
//get column count present in the sheet
int colcount = sheet.getRow(1).getLastCellNum();
System.out.println(" Total number of columns present in the sheet : "+colcount);
//get the data from sheet by iterating through cells
//by using for loop
for(int i = 1; i<=rowcount; i++)
{
XSSFCell cell = sheet.getRow(i).getCell(1);
String celltext="";
//Get celltype values
if(cell.getCellType()==Cell.CELL_TYPE_STRING)
{
celltext=cell.getStringCellValue();
}
else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC)
{
celltext=String.valueOf(cell.getNumericCellValue());
}
else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
{
celltext="";
}
//Check the age and set the Cell value into excel
if(Double.parseDouble(celltext)>=18)
{
sheet.getRow(i).getCell(2).setCellValue("Major");
}
else
{
sheet.getRow(i).getCell(2).setCellValue("Minor");
}
}//End of for loop
//close the file input stream
fis.close();
//Open an excel to write the data into workbook
FileOutputStream fos = new FileOutputStream("D:\\Testing_Team\\Age_Validation.xlsx");
//Write into workbook
wb.write(fos);
//close fileoutstream
fos.close();
}
}
*I am getting error like [ Exception in thread "main" java.lang.NullPointerException
at demo.Readwrite.main(Readwrite.java:31) ] .
Can Someone please guide me for the same.
I have watched this video for reference https://www.youtube.com/watch?v=orYZB_RUgNc
I have added two poi dependency also poi-ooxml and poi.
Waiting for your valuable response.*
As you comment shows that, you should send index number rather than column name,
I think 'Age' is a column name of you sheet.
//get the sheet from the workbook by index
XSSFSheet sheet = wb.getSheetAt(0);
please replace above line in you code and run it.
I am a beginner in Java coding and would like to know how to read the following excel sheet data using Java.
Also, I have tried the below code -
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadingFromExcelSheet {
public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
FileInputStream ip = new FileInputStream("C:\\Users\\Sanjana Rajeev\\Desktop\\Murali_YoutubeLinks.xlsx");
Workbook wb = WorkbookFactory.create(ip);
Sheet sheet = wb.getSheet("MySheet1");
int i,j;
int rowcount =3,cellcount=2;
for ( i=0;i<=rowcount;i++){
for (j=0;j<cellcount;j++){
Row row = sheet.getRow(i);
Cell cell = row.getCell(j);
String cellval = cell.getStringCellValue();
System.out.println(cellval + "\t\t" );
}
}
ip.close();
}
}
And i am getting the below shown output :
Topics
YouTube Links
Java Execution
Java and JDK dowload
Eclipse download
Create a Workspace/Project/Package/Class files
https://youtu.be/Pvcv-V69Vc0
Java Execution
Java and JDK dowload
Eclipse download
Create a Workspace/Project/Package/Class files
Datatypes
Variables
String Concatenation
https://youtu.be/Gx0ubuYwTjg
Global Variables (Static & NonStatic)
Local Variables
Memory Allocation
I am getting the values of the cell but not in their proper order as like the excel sheet. Can anyone please help?
Try this approach
public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
FileInputStream ip = new FileInputStream("C:\\Users\\Sanjana Rajeev\\Desktop\\Murali_YoutubeLinks.xlsx");
Workbook wb = WorkbookFactory.create(ip);
Sheet sheet = wb.getSheet("MySheet1");
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//iterate over the columns of the current row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
//append empty line
System.out.println();
}
ip.close();
}
Does this improve the formatting?
for ( i=0;i<=rowcount;i++)
{
Row row = sheet.getRow(i);
for (j=0;j<cellcount;j++)
{
Cell cell = row.getCell(j);
String cellval = cell.getStringCellValue();
System.out.print(cellval + "\t\t" );
}
System.out.println();
}
why is not possible to 'properly' hide an Excel row using Apache POI (3.16)? It is just possible to call (XSSFRow) row.setZeroHeight(), which is also what the Busy developer's guide recommends. However, this is not the same as hiding the row the way Excel does it. You can 'Hide' and 'Unhide' rows with the respective context menu options.
I thought setting the row style should work, but it doesn't. In the resulting Excel file, the row can still be seen.
package de.mwe;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.Assert;
import org.testng.annotations.Test;
public class MWE {
#Test
public void testHidingRows() {
final XSSFWorkbook wb = new XSSFWorkbook();
String sname = "HideRowsTestSheet", cname = "TestName", cvalue = "TestVal";
XSSFSheet sheet = wb.createSheet( sname );
XSSFRow row = sheet.createRow( 0 );
XSSFCell cell = row.createCell( (short) 0 );
cell.setCellValue( cvalue );
XSSFCellStyle hiddenRowStyle = wb.createCellStyle();
hiddenRowStyle.setHidden( true );
row.setRowStyle( hiddenRowStyle );
Assert.assertTrue( row.getRowStyle().getHidden() );
try (FileOutputStream fileOut = new FileOutputStream( new File( "target/PoiTestDrive.xlsx" ) )) {
wb.write( fileOut );
} catch ( IOException ex ) {
ex.printStackTrace();
}
// does not work, resulting Excel file shows first row.
}
}
The Busy developer's guide is correct for hiding/unhiding rows. But there is a little error since it must be row.setZeroHeight(true); for hiding a row.
The Row.setZeroHeight(boolean) does exactly what Excel does while hiding a row. It works for HSSF as well as for XSSF. For XSSF it simply sets hidden property to the rows XML, see XSSFRow.java.
Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
public class CreateExcelHiddenRow {
public static void main(String[] args) throws Exception {
//Workbook wb = new HSSFWorkbook();
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
for (int r = 0; r < 3; r++) {
Row row = sheet.createRow(r);
Cell cell = row.createCell(0);
cell.setCellValue("Row " + (r+1));
}
Row row = sheet.getRow(1);
row.setZeroHeight(true);
//FileOutputStream out = new FileOutputStream("CreateExcelHiddenRow.xls");
FileOutputStream out = new FileOutputStream("CreateExcelHiddenRow.xlsx");
wb.write(out);
out.close();
wb.close();
}
}
You create a new row style. Instead, fetch the rows' existing Style and add your rule:
currentRow.getRowStyle().setHidden(true);
You kinda can refer to this post
Edit: You even create a new CellStyle as #RC mentioned.
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);
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) {
}
}
}