Read Write Excel File in java - java

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.

Related

Excel import from csv file to convert

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

Selenium Webdriver: Writing file to excel fails even though value is fetched properly from other excel

Please find the attached code snippet and please help me to proceed with this. I am trying to read data from one excel and then write the same to another excel , while trying to write the file it's stopping the code. When I tried debugging I could see that value is properly fetched but write is not working.
package Export;
import java.io.File;
import java.io.FileInputStream;
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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestExport
{
XSSFWorkbook xlsxworkbook;
HSSFWorkbook xlsworkbook;
XSSFWorkbook xlsxworkbook1;
HSSFWorkbook xlsworkbook1;
Sheet sheet;
Sheet sheet1;
TestExport(){
xlsxworkbook=null;
xlsworkbook=null;
sheet=null;
xlsxworkbook1=null;
xlsworkbook1=null;
sheet1=null;
}
public void readExcel(String filePath,String fileName,String sheetName,String filePath1,String fileName1,String sheetName1)
{
try{
FileInputStream fs=new FileInputStream(new File("C:\\Users\\Susmitha-Phases\\Desktop\\TestWorkbook.xlsx"));
FileOutputStream fi=new FileOutputStream(new File("C:\\Users\\Susmitha-Phases\\Desktop\\TestWorkbook1.xlsx"));
fs.toString();
if(fileName.toLowerCase().endsWith("xlsx")){
xlsxworkbook = new XSSFWorkbook(fs);
sheet=xlsxworkbook.getSheet(sheetName);
xlsxworkbook1 = new XSSFWorkbook();
sheet1=xlsxworkbook.getSheet(sheetName1);
}
else{
xlsworkbook=new HSSFWorkbook(fs);
sheet=xlsworkbook.getSheet(sheetName);
xlsworkbook1=new HSSFWorkbook();
sheet1=xlsworkbook.getSheet(sheetName1);
}
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
//Create a loop over all the rows of excel file to read it
for (int i = 0; i < rowCount+1; i++)
{
Row row = sheet.getRow(i);
Row row1=sheet1.getRow(i);
//Create a loop to print cell values in a row
for (int j = 0; j < row.getLastCellNum(); j++)
{
String temp= row.getCell(j).getStringCellValue();
row1.createCell(i).setCellValue(temp);
//Print Excel data in console
System.out.print(row1.getCell(j).getStringCellValue()+"|| ");
xlsworkbook.write(fi);
//System.out.print(row.getCell(j).getStringCellValue()+"|| ");
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws IOException{
//Create an object of ReadGuru99ExcelFile class
TestExport objExcelFile = new TestExport();
//Prepare the path of excel file
String filePath = System.getProperty("C:\\Users\\Susmitha-Phases\\Desktop\\TestWorkbook.xlsx");
String filePath1 = System.getProperty("C:\\Users\\Susmitha-Phases\\Desktop\\TestWorkbook1.xlsx");
//Call read file method of the class to read data
objExcelFile.readExcel(filePath,"TestWorkbook.xlsx","Sheet1",filePath1,"TestWorkbook1.xlsx","Sheet1");
}
}
There are some problem with your code it possible throw null pointer exception
You never created the instance for xlsworkbook in your class when the file type xlsx and trying to write the file . which is wrong will throw definitely null pointer exception. so You must change the logic while writing which file type should be write . Probably you can check file type and write the file.

Can't read Excel 2010 file with Apache POI. First Row number is -1

I am trying the this testfile with the Apache POI API (current version 3-10-FINAL). The following test code
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelTest {
public static void main(String[] args) throws Exception {
String filename = "testfile.xlsx";
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(filename));
XSSFSheet sheet = wb.getSheetAt(0);
System.out.println(sheet.getFirstRowNum());
}
}
results in the first row number to be -1 (and existing rows come back as null). The test file was created by Excel 2010 (I have no control over that part) and can be read with Excel without warnings or problems. If I open and save the file with my version of Excel (2013) it can be read perfectly as expected.
Any hints into why I can't read the original file or how I can is highly appreciated.
The testfile.xlsx is created with "SpreadsheetGear 7.1.1.120". Open the XLSX file with a software which can deal with ZIP archives and look into /xl/workbook.xml to see that. In the worksheets/sheet?.xml files is to notice that all row elements are without row numbers. If I put a row number in the first row-tag like <row r="1"> then apache POI can read this row.
If it comes to the question, who is to blame for this, then the answer is definitely both Apache Poi and SpreadsheetGear ;-). Apache POI because the attribute r in the row element is optional. But SpreadsheetGear also because there is no reason not to use the r attribute if Excel itself does it ever.
If you cannot get the testfile.xlsx in a format which can Apache POI read directly, then you must work with the underlying objects. The following works with your testfile.xlsx:
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.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow;
import java.util.List;
class Testfile {
public static void main(String[] args) {
try {
InputStream inp = new FileInputStream("testfile.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
System.out.println(sheet.getFirstRowNum());
CTWorksheet ctWorksheet = ((XSSFSheet)sheet).getCTWorksheet();
CTSheetData ctSheetData = ctWorksheet.getSheetData();
List<CTRow> ctRowList = ctSheetData.getRowList();
Row row = null;
Cell[] cell = new Cell[2];
for (CTRow ctRow : ctRowList) {
row = new MyRow(ctRow, (XSSFSheet)sheet);
cell[0] = row.getCell(0);
cell[1] = row.getCell(1);
if (cell[0] != null && cell[1] != null && cell[0].toString() != "" && cell[1].toString() != "")
System.out.println(cell[0].toString()+"\t"+cell[1].toString());
}
} catch (InvalidFormatException ifex) {
} catch (FileNotFoundException fnfex) {
} catch (IOException ioex) {
}
}
}
class MyRow extends XSSFRow {
MyRow(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow row, XSSFSheet sheet) {
super(row, sheet);
}
}
I have used:
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRow
Which are part of the Apache POI Binary Distribution poi-bin-3.10.1-20140818 and there are within poi-ooxml-schemas-3.10.1-20140818.jar
For a documentation see http://grepcode.com/snapshot/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/
And I have extend XSSFRow, because we can't use the XSSFRow constructor directly since it has protected access.

Read xlsx file with POI (SXSSFWorkbook)

I'm trying to do my first tests of reading large xlsx file with POI, but to do a simple test with a small file I fail to show the value of a cell.
Someone can tell me what is my mistake. All the suggestions are welcome. Thanks.
Test.java:
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) throws Throwable {
File file = new File("/tmp/test.xlsx");
OPCPackage pkg = OPCPackage.open(new FileInputStream(file.getAbsolutePath()));
XSSFWorkbook xssfwb = new XSSFWorkbook(pkg);
SXSSFWorkbook wb = new SXSSFWorkbook(xssfwb, 100);
Sheet sh = wb.getSheet("Hola");
System.out.println("Name: "+sh.getSheetName()); // Line 19
System.out.println("Val: "+sh.getRow(1).getCell(1).getStringCellValue()); // Line 20
}
}
Result:
Name: Hola
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:20)
test.xlsx:
Please consult: similar question SXSSFWorkBook is write only, it doesn't support reading.
For low memory reading of .xlsx files, you should look at the XSSF and SAX EventModel documentation : Gagravarr
If memory wouldn't be an issue you could use a XSSFSheet instead e.g.
File file = new File("D:/temp/test.xlsx");
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sh = wb.getSheet("Hola");
System.out.println(sh.getLastRowNum());
System.out.println("Name: "+sh.getSheetName());
Row row = sh.getRow(1);
System.out.println(row.getRowNum());
System.out.println("Val: "+sh.getRow(1).getCell(1).getStringCellValue());
I too faced the same issue of OOM while parsing xlsx file...after two days of struggle, I finally found out the below code that was really perfect;
This code is based on sjxlsx. It reads the xlsx and stores in a HSSF sheet.
// read the xlsx file
SimpleXLSXWorkbook = new SimpleXLSXWorkbook(new File("C:/test.xlsx"));
HSSFWorkbook hsfWorkbook = new HSSFWorkbook();
org.apache.poi.ss.usermodel.Sheet hsfSheet = hsfWorkbook.createSheet();
Sheet sheetToRead = workbook.getSheet(0, false);
SheetRowReader reader = sheetToRead.newReader();
Cell[] row;
int rowPos = 0;
while ((row = reader.readRow()) != null) {
org.apache.poi.ss.usermodel.Row hfsRow = hsfSheet.createRow(rowPos);
int cellPos = 0;
for (Cell cell : row) {
if(cell != null){
org.apache.poi.ss.usermodel.Cell hfsCell = hfsRow.createCell(cellPos);
hfsCell.setCellType(org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING);
hfsCell.setCellValue(cell.getValue());
}
cellPos++;
}
rowPos++;
}
return hsfSheet;

java program to read specific data

I need java code to read data for specific column from excel sheet. – (lo number, line, voucher no, stloc , quantity ,activity.)
These set of values for a particular column will be used for sql query (jdbc-odbc connection done).
The output for the query will be matched with a column in this sheet (this part ll be done later)
Kindly help.
sample excel sheet
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package excelfilereading;
/**
*
* #author vkantiya
*/
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class Main {
#SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
//
// An excel file name. You can create a file name with a full
// path information.
//
String filename = "FirstExcel.xls";
// Create an ArrayList to store the data read from excel sheet.
//
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
//
// Create a FileInputStream that will be use to read the
// excel file.
//
fis = new FileInputStream(filename);
//
// Create an excel workbook from the file system.
//
HSSFWorkbook workbook = new HSSFWorkbook(fis);
//
// Get the first sheet on the workbook.
//
HSSFSheet sheet = workbook.getSheetAt(0);
//
// When we have a sheet object in hand we can iterator on
// each sheet's rows and on each row's cells. We store the
// data read on an ArrayList so that we can printed the
// content of the excel to the console.
//
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
showExelData(sheetData);
}
private static void showExelData(List sheetData) {
//
// Iterates the data and print it out to the console.
//
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
for (int j = 0; j < list.size(); j++) {
HSSFCell cell = (HSSFCell) list.get(j);
System.out.print(
cell.getRichStringCellValue().getString());
if (j < list.size() - 1) {
System.out.print(", ");
}
}
System.out.println("");
}
}
}
Have a look at Apache POI - the Java API for Microsoft Documents.
It covers
Excel (SS=HSSF+XSSF)
Word (HWPF+XWPF)
PowerPoint (HSLF+XSLF)
OpenXML4J (OOXML)
OLE2 Filesystem (POIFS)
OLE2 Document Props (HPSF)
Outlook (HSMF)
Visio (HDGF) TNEF (HMEF)
Publisher (HPBF)

Categories

Resources