FileWriter stops unexpectedly - java

I am trying to use XLS2CSV to convert an Excel file to a csv text file. I modified the existing class slightly to change PrintStream to Writer so I could write to a file using FileWriter.
Anyway, it writes to the System.out.PrintStream fine, everything shows up. But when I open the file the last few lines are missing. My first assumption was that the application was closing the connection before it could complete the writes but I used an infinite loop to try and test that but even leaving the application open it does the same thing.
Does anyone have any ideas why this will print to PrintStream fine but not write to a file? I changed the FileWriter to CSVWriter and it seemed to write less data so I'm thinking it does have something to do with the connection getting closed but I'm fairly new to input and output so any help would be appreciated.
Here is a functional example (you'll need to modify the file name for the input and output)
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
public class XLS2CSV {
private InputStream in;
private Writer out;
private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
public XLS2CSV(InputStream in, Writer out) {
if (null == in) {
throw new IllegalArgumentException("in cannot be null.");
}
if (null == out) {
throw new IllegalArgumentException("out cannot be null.");
}
this.in = in;
this.out = out;
}
public void process() throws IOException {
process(in);
}
private void process(InputStream in) throws IOException {
HSSFWorkbook w = new HSSFWorkbook(in);
int numSheets = w.getNumberOfSheets();
for (int i = 0; i < numSheets; i++) {
HSSFSheet sheet = w.getSheetAt(i);
int lastRow = 0;
for (Iterator rows = sheet.rowIterator(); rows.hasNext();) {
Row row = (Row) rows.next();
int lastCol = 0;
for (Iterator cells = row.cellIterator(); cells.hasNext();) {
Cell cell = (Cell) cells.next();
String cellValue = "";
switch (cell.getCellType()) {
case Cell.CELL_TYPE_FORMULA:
FormulaEvaluator fe = new HSSFFormulaEvaluator(w);
CellValue v = fe.evaluate(cell);
switch (v.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
cellValue = String.valueOf(v.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
cellValue = String.valueOf(v.getNumberValue());
break;
case Cell.CELL_TYPE_STRING:
cellValue = String.valueOf(v.getStringValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case Cell.CELL_TYPE_FORMULA:
break;
}
break;
case Cell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
cellValue = dateFormat.format(date);
} else {
cellValue = String.valueOf(cell);
}
break;
default:
cellValue = String.valueOf(cell);
}
int cellIndex = cell.getColumnIndex();
while (lastCol < cellIndex) {
System.out.print(",");
out.append(",");
lastCol++;
}
System.out.print(cellValue);
out.append(cellValue);
}
while (lastRow <= row.getRowNum()) {
System.out.println();
out.append('\n');
lastRow++;
}
}
}
}
public void setDateFormat(DateFormat dateFormat) {
if (null == dateFormat) {
throw new IllegalArgumentException("dateFormat cannot be null.");
}
this.dateFormat = dateFormat;
}
public DateFormat getDateFormat() {
return dateFormat;
}
public static void process(File file, Writer out) throws IOException {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
new XLS2CSV(new BufferedInputStream(fis), out).process();
} finally {
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
File xlsFile = new File("C:/Documents and Settings/berlgeof/Desktop/Commit Dates 12-10-2013.xls");
if (!xlsFile.exists()) {
System.err.println("Not found or not a file: " + xlsFile.getPath());
return;
}
Writer writer = null;
try {
writer = new FileWriter("lib/files/converted/Temp Commit Data.csv");
} catch (IOException e) {
e.printStackTrace();
}
XLS2CSV xls2csv = null;
try {
xls2csv = new XLS2CSV(new FileInputStream(xlsFile), writer);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
xls2csv.process();
} catch (IOException e) {
e.printStackTrace();
}
// while(true) {} // Let me close the application
}

You're not closing the writer, which means there's data still in the buffer. You should close it (and all the other streams etc) in finally blocks, or use a try-with-resources statement if you're using Java 7.
Also note that the way you're currently "handling" exceptions is to pretty much ignore them and proceed - which means that after one thing's failed, you'll almost certainly get another failure. Rip out those try/catch blocks, and just let the exception propagate up. (Declare that your main method can throw IOException.)

Related

Unable to write to Excel using Selenium webdriver

I have created a test where I am reading from excel and iterating through a worksheet to process an application in a web portal. This is working as expected.
However I am now trying to write results from the web page into another sheet on the same excel. The test case I am running passes in Eclipse but no data is written to the specified sheet. (I'm also looking to iterate on the results sheet to capture multiple application records, haven't got to that part yet).
Please see below my test script and the methods I have created in an ExcelConfig util sheet. Hoping someone can advise where I'm going wrong, thanks in advance.
Steve
Test Case
package com.htb.puma.uatTests;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import com.htb.puma.pages.SMcaseHeader;
import com.htb.puma.pages.SMhome;
import com.htb.puma.pages.SMloanDetails;
import com.htb.puma.pages.SMlogin;
import com.htb.puma.pages.SetUpConfig;
import com.htb.puma.util.ExcelConfig;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import java.io.File;
import java.io.IOException;
public class THAM_WRITE_Test {
WebDriver driver;
#Test
public void specMortHome() throws NoAlertPresentException, InterruptedException, IOException {
// calling drivers from the SetUpConfig page
driver = SetUpConfig.getChromeDriver();
// driver = SetUpConfig.getFirefoxDriver();
// driver = SetUpConfig.getIEDriver();
String path = new File("src/test/resources/TestData.xlsx").getAbsolutePath();
ExcelConfig excel = new ExcelConfig(path);
int row = 1;
while (excel.getData("PDFRollUp", row, 0) != "") {
String loanAmReq = excel.getNumericData("PDFRollUp", row, 6);
// LOGIN
SMlogin specMortLogin = new SMlogin(driver);
specMortLogin.openSMlogin();
specMortLogin.maximiseWindow();
specMortLogin.enterUsername("OpsAdminAuto");
specMortLogin.enterPassword("AutoOps123!");
specMortLogin.clickSignInBtn();
Thread.sleep(2000);
SMhome specMortHome = new SMhome(driver);
specMortHome.clickTopMC();
Thread.sleep(2000);
SMcaseHeader specMortCaseHeader = new SMcaseHeader(driver);
specMortCaseHeader.clickLoanDetailsTab();
SMloanDetails specMortLoanDetails = new SMloanDetails(driver);
Thread.sleep(2000);
specMortLoanDetails.enterLoanAmReq(Keys.CONTROL + "a"); // PDF
specMortLoanDetails.enterLoanAmReq(loanAmReq); // PDF
String erc = specMortLoanDetails.getERC();
String ltv = specMortLoanDetails.getLTV();
excel.createFile("src/test/resources/TestData.xlsx");
excel.writeStringData("Results", 1, 1, erc);
excel.writeStringData("Results", 1, 2, ltv);
specMortHome.clickUserActionsHomeLM();
specMortHome.clickLogoutHomeLM();
row++;
}
driver.quit();
}
}
Excel Config
package com.htb.puma.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
public class ExcelConfig {
public XSSFWorkbook wb;
XSSFSheet sheet1;
public ExcelConfig(String Excelpath) {
File src = new File(Excelpath);
try {
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
System.out.println("Excel file not loaded");
}
}
// reads the string in the excel file
public String getData(String sheetName, int row, int column) {
sheet1 = wb.getSheet(sheetName);
String data = "";
try {
data = sheet1.getRow(row).getCell(column).getStringCellValue();
} catch (NullPointerException e) {
data = "";
}
return data;
}
// reads the number in the excel file
public String getNumericData(String sheetName, int row, int column) {
sheet1 = wb.getSheet(sheetName);
String data = "";
try {
// data = sheet.getRow(row).getCell(column).getRawValue();
DataFormatter dataFormatter = new DataFormatter();
Cell cell = sheet1.getRow(row).getCell(column);
data = dataFormatter.formatCellValue(cell);
} catch (NullPointerException e) {
data = "";
}
return data;
}
//write string data into excel
public void writeStringData(String sheetName, int row, int column, String data) {
sheet1 = wb.getSheet(sheetName);
Row valueRow = sheet1.getRow(row);
Cell valueCell = valueRow.createCell(column);
if (data.equals("FAILED")) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
//font.setColor(HSSFColor.RED.index);
style.setFont(font);
valueCell.setCellValue(data);
valueCell.setCellStyle(style);
}
valueCell.setCellValue(data);
}
//creates an excel file
public void createFile(String path) {
File src = new File(path);
try {
FileOutputStream outputStream = new FileOutputStream(src);
try {
wb.write(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
write(java.io.OutputStream stream) is used to write data to the excel file
public void writeStringData(String sheetName, int row, int column, String data) {
try {
sheet1 = wb.getSheet(sheetName);
Row valueRow = sheet1.getRow(row);
Cell valueCell = valueRow.createCell(column);
if (data.equals("FAILED")) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
//font.setColor(HSSFColor.RED.index);
style.setFont(font);
valueCell.setCellValue(data);
valueCell.setCellStyle(style);
}
valueCell.setCellValue(data);
FileOutputStream fout;
fout = new FileOutputStream(new File("<path>"));
//fout = new FileOutputStream("src/test/resources/TestData.xlsx" );
wb.write(fout);
// fout.flush();
wb.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EncryptedDocumentException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

On calling getcellData() getting no values from excel - Selenium WebDriver

Here is my excel utils class:
package utility;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.CellType;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell cell;
private static XSSFRow row;
//This method is to set the File path and to open the Excel
file, Pass Excel Path and Sheetname as Arguments to this method
public static void setExcelFile(String Path, String SheetName) throws Exception {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(Path);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
String cellData = "";
cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
cell.setCellType(CellType.STRING);
cellData = cell.getStringCellValue();
return cellData;
} catch (Exception e) {
return "undefined";
}
}
//This method is to write in the Excel cell, Row num and Col num are the parameters
public static void setCellData(String Result, int RowNum, int ColNum) throws Exception {
try {
row = ExcelWSheet.getRow(RowNum);
cell = row.getCell(ColNum, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (cell == null) {
cell = row.createCell(ColNum);
cell.setCellValue(Result);
} else {
cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
FileOutputStream fileOut = new FileOutputStream(Constants.Path_TestData + Constants.File_TestData);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
throw (e);
}
}
}
Here is the script where I'm calling the getCellData to get the values from Excel:
String cellData = ExcelUtils.getCellData(1, 1);
System.out.println("CellData :" + cellData);
Here is the excel file format:
TestCaseName | Username | Password
TC_01 | TestData |
Output:
Exception in thread "main" java.lang.NullPointerException
at utility.ExcelUtils.getCellData(ExcelUtils.java:63)
at testScripts.Category_creation.main(Category_creation.java:47)
Here is the excel I'am using. Not able to fetch data from excel file. I'm using Page object framework, hence the excel utils file contains only the code and in fetching the data in testScript by passing row and column number.
POI 3.9
please add cell.setCellType(Cell.CELL_TYPE_STRING); after cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
i.e.
import org.apache.poi.ss.usermodel.Cell;
...
try{
cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
cell.setCellType(Cell.CELL_TYPE_STRING);
String CellData = cell.getStringCellValue();
return CellData;
}catch (Exception e){
return"";
}
or you can use this construct
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
source http://www.java67.com/2014/09/how-to-read-write-xlsx-file-in-java-apache-poi-example.html
and please rename the variable private static XSSFCell Cell; to cell. (Variable naming conventions in Java?)
UPDATE 1
POI 3.17 you could also uncomment switch-case block, it works for POI 3.17
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Excel {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell xCell;
private static XSSFRow xRow;
public static void main(String... args) {
try {
InputStream is = readInputStreamFromFile();
XSSFWorkbook myWorkBook = new XSSFWorkbook(is);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
ExcelWSheet = mySheet;
System.out.println(getCellData(1, 0));
System.out.println(getCellData(1, 1));
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getCellData(int RowNum, int ColNum) throws Exception{
try {
String cellData = "";
xCell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
xCell.setCellType(CellType.STRING);
cellData = xCell.getStringCellValue();
// switch (xCell.getCellTypeEnum()) {
// case STRING:
// //System.out.print(xCell.getStringCellValue() + "\t");
// cellData = xCell.getStringCellValue();
// break;
// case NUMERIC:
// cellData = String.valueOf(xCell.getNumericCellValue());
// //System.out.print(xCell.getNumericCellValue() + "\t");
// break;
// case BOOLEAN:
// cellData = String.valueOf(xCell.getBooleanCellValue());
// //System.out.print(xCell.getBooleanCellValue() + "\t");
// break;
//
// default:
// cellData = "undefined";
// }
return cellData;
} catch (Exception e){
return "undefined";
}
}
private static InputStream readInputStreamFromFile() throws Exception {
try {
File f = new File("C:\\path to your file\\TestData.xlsx");
InputStream is = new FileInputStream(f);
try {
return new ByteArrayInputStream(IOUtils.toByteArray(is));
} finally {
is.close();
}
} catch (IOException e) {
throw new Exception(e);
}
}
}

Read/Write Data from Text To Excel and print NEXT,PREV,Current Line according to conditions [duplicate]

This question already has answers here:
Java Scanner to print previous and next lines
(2 answers)
Closed 6 years ago.
I have a text file from which according to some keywords I have to read that line and write that line into excel file. I did this, now I need to read next line and previous line and that lines also I need to write into excel sheet in different columns. How can I do this.
rahul1.txt
ABCD1 abhishek1 duplicatevalue jgf
ABCD2 abhishek2 duplicatevalue jgf
ABCD3 abhishek3 duplicatevalue jgf
ABCD4 abhishek4 duplicatevalue jgf
while (st1.hasMoreTokens()) {String txt = st1.nextToken();if (txt.contains("abhishek2")) {l1.add(txt);}
How can I print
ABCD1 abhishek1 duplicatevalue jgf prev Line
and
ABCD3 abhishek3 duplicatevalue jgf Next Line
in different column?
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;`
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ReadWrite {
int rownum = 1;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
File exactFile;
boolean retu;
// BufferedReader reader = null;
{
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("SampleSheet");
Row headerRow = firstSheet.createRow(0);
// headerRow.createCell(0).setCellValue("#");
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue(Message");
headerRow.createCell(2).setCellValue("name");
headerRow.createCell(3).setCellValue("address");
headerRow.createCell(4).setCellValue("contact");
headerRow.createCell(5).setCellValue("Next");
headerRow.createCell(6).setCellValue("Prev");
}
public static void main(String args[]) {
ReadWrite class2 = new ReadWrite();
class2.readfile();
}
void readfile() {
try {
FileInputStream fInput = new FileInputStream(
"D:\\Rahul\\rahul1.txt");
DataInputStream dis = new DataInputStream(fInput);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String lineStr;
String prevStr = "";
String nextStr = "";
//List<String> l1 = new ArrayList<String>();
int i;
int seqno = 1;
while ((lineStr = br.readLine()) != null) {
List<String> l1 = new ArrayList<String>();
if (lineStr.contains("Oracle")
|| lineStr.contains("SAP")
|| lineStr.contains("J2EE")) {
l1.add("C1");
l1.add(lineStr);
l1.add("M1");
l1.add("R1");
l1.add("V1");
l1.add(nextStr);
l1.add(prevStr);
} else {
prevStr = lineStr;
}
try {
if (l1 != null && l1.size() > 0)
retu = writenameinsheet(l1);
} catch (Exception e) {
e.printStackTrace();
}
seqno++;
i = 1;
}br.close();
FileOutputStream fos = null;
try {
File excelFile = new File("D:\\Rahul\\rahul.xls");
fos = new FileOutputStream(excelFile);
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
boolean writenameinsheet(List<String> l1) throws Exception {
try {
Row row = firstSheet.createRow(rownum);
for (int j = 0; j < l1.size(); j++){
Cell cell = row.createCell(j);
cell.setCellValue(l1.get(j));
}rownum++;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return true;
}
}

Reading multiple tabs of a huge excel file in Java using XSS and Event

I am using this code from (by author: lchen) which reads contents from excel file based on number of rows I provide into method 'readRow()'.
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.InputSource;
public class TestLargeFileRead {
private int rowNum = 0;
private OPCPackage opcPkg;
private ReadOnlySharedStringsTable stringsTable;
private XMLStreamReader xmlReader;
public void XExcelFileReader(String excelPath) throws Exception {
opcPkg = OPCPackage.open(excelPath, PackageAccess.READ);
this.stringsTable = new ReadOnlySharedStringsTable(opcPkg);
XSSFReader xssfReader = new XSSFReader(opcPkg);
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream inputStream = xssfReader.getSheetsData().next();
xmlReader = factory.createXMLStreamReader(inputStream);
while (xmlReader.hasNext()) {
xmlReader.next();
if (xmlReader.isStartElement()) {
if (xmlReader.getLocalName().equals("sheetData"))
break;
}
}
}
public int rowNum() {
return rowNum;
}
public List<String[]> readRows(int batchSize) throws XMLStreamException {
String elementName = "row";
List<String[]> dataRows = new ArrayList<String[]>();
if (batchSize > 0) {
while (xmlReader.hasNext()) {
xmlReader.next();
if (xmlReader.isStartElement()) {
if (xmlReader.getLocalName().equals(elementName)) {
rowNum++;
dataRows.add(getDataRow());
if (dataRows.size() == batchSize)
break;
}
}
}
}
return dataRows;
}
private String[] getDataRow() throws XMLStreamException {
List<String> rowValues = new ArrayList<String>();
while (xmlReader.hasNext()) {
xmlReader.next();
if (xmlReader.isStartElement()) {
if (xmlReader.getLocalName().equals("c")) {
CellReference cellReference = new CellReference(
xmlReader.getAttributeValue(null, "r"));
// Fill in the possible blank cells!
while (rowValues.size() < cellReference.getCol()) {
rowValues.add("");
}
String cellType = xmlReader.getAttributeValue(null, "t");
rowValues.add(getCellValue(cellType));
}
} else if (xmlReader.isEndElement()
&& xmlReader.getLocalName().equals("row")) {
break;
}
}
return rowValues.toArray(new String[rowValues.size()]);
}
private String getCellValue(String cellType) throws XMLStreamException {
String value = ""; // by default
while (xmlReader.hasNext()) {
xmlReader.next();
if (xmlReader.isStartElement()) {
if (xmlReader.getLocalName().equals("v")) {
if (cellType != null && cellType.equals("s")) {
int idx = Integer.parseInt(xmlReader.getElementText());
return new XSSFRichTextString(
stringsTable.getEntryAt(idx)).toString();
} else {
return xmlReader.getElementText();
}
}
} else if (xmlReader.isEndElement()
&& xmlReader.getLocalName().equals("c")) {
break;
}
}
return value;
}
#Override
protected void finalize() throws Throwable {
if (opcPkg != null)
opcPkg.close();
super.finalize();
}
public static void main(String[] args) {
try {
TestLargeFileRead howto = new TestLargeFileRead();
howto.XExcelFileReader("D:\\TEMP_CATALOG\\H1.xlsx");
} catch (Exception e) {
e.printStackTrace();
}
}
}
But it reads only First SHEET's contents and discards other subsequent SHEETS. My requirement is to read SHEET name; and based on name read that SHEET's contents. Can anyone help me to customize this above code fetch SHEET NAME and their contents ? please ?
The key class you need to work with, and tweak your use of, is XSSFReader. If you take a look at the Javadocs for it, you'll see it provides an Iterator of InputStreams of all the sheets, and a way to get at the root Workbook stream.
If you want to access all the sheets, you need to change these lines:
InputStream inputStream = xssfReader.getSheetsData().next();
xmlReader = factory.createXMLStreamReader(inputStream);
Into something more like:
Iterator<InputStream> sheetsData = xssfReader.getSheetsData();
while (sheetsData.hasNext()) {
InputStream inputStream = sheetsData.next();
xmlReader = factory.createXMLStreamReader(inputStream);
....
}
If you also want to get the sheet name as well, you'll want to do something like what is shown in the Apache POI XLSX event-based text extractor
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
while (sheetsData.hasNext()) {
InputStream inputStream = sheetsData.next();
String sheetName = iter.getSheetName();
if (sheetName.equalsIgnoreCase("TheSheetIWant")) {
xmlReader = factory.createXMLStreamReader(inputStream);
....
}
}
If you want to know more about doing this stuff, then one of the best examples, that's easy to read and follow, is XSSFEventBasedExcelExtractor that comes with Apache POI - read the code for that and learn!

Issue while reading Excel document (Java code)

I have some Java code which reads the Excel data. On running the Java code, it's showing the following error. Help me resolve the same. Also, I need to know other method of reading .xlsx file.
(A small edit) how I can print rows with their respective columns. For example:
Age
19
20
21
Salary
35k
20k
40k
.
.
.
Exception in thread "main"
org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied
data appears to be in the Office 2007+ XML. You are calling the part
of POI that deals with OLE2 Office Documents. You need to call a
different part of POI to process this data (eg XSSF instead of HSSF)
at
org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:131)
at
org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:104)
at
org.apache.poi.poifs.filesystem.POIFSFileSystem.(POIFSFileSystem.java:138)
at
org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:322)
at
org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:303)
at ExcelRead.main(ExcelRead.java:18)
The Java code is as follows:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ExcelRead {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:/Users/vinayakp/Desktop/Book.xlsx"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException ae) {
ae.printStackTrace();
}
}
}
If you want to read a .xls file you must use HSSF (it supports only .xls format) but for .xlsx files you must use XSSF or another higher version API.
After deleting previous imports class then try to add
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;
private static void read(String path){
Workbook workbook = null;
FileInputStream fis = null;
try {
File source = new File(path);
if(source.exists()){
fis = new FileInputStream(source);
workbook = WorkbookFactory.create(source);
}else{
JOptionPane.showMessageDialog(null, "File path is not exist.", "Error", JOptionPane.ERROR_MESSAGE);
}
Sheet sheet = null;
int lastRowNum = 0;
int numSheets = workbook.getNumberOfSheets();
for(int i = 0; i < numSheets; i++) {
sheet = workbook.getSheetAt(i);
if(sheet.getPhysicalNumberOfRows() > 0) {
lastRowNum = sheet.getLastRowNum();
int lastCellNum = 0;
for(Row row : sheet) {
Employee emp = new Employee();
int numOfCell = row.getPhysicalNumberOfCells();
System.out.println("numOfCell:: "+numOfCell);
String stringValues [] = new String[numOfCell];
for(Cell cell : row) {
// cell = row.getCell(cellIndex);
int cellIndex = cell.getColumnIndex();
logger.info("cellIndex:: "+ cellIndex);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_FORMULA:
// printValue = "FORMULA value=" + cell.getCellFormula();
stringValues[cellIndex] = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
//printValue = "NUMERIC value=" + cell.getNumericCellValue();
System.out.println("Value is numeric:: "+ cell.getNumericCellValue());
stringValues[cellIndex] = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
// printValue = "STRING value=" + cell.getStringCellValue();
stringValues[cellIndex] = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BLANK:
// printValue = "STRING value=" + cell.getStringCellValue();
stringValues[cellIndex] = cell.getStringCellValue();
break;
default:
}
}
}
}
}
}
} catch (InvalidFormatException e) {
logger.error(e.getMessage());
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
}
finally {
if (fis != null) {
try {
fis.close();
fis = null;
} catch (IOException ioEx) {
logger.error(ioEx.getMessage());
}
}
}
}
you are using the wrong class for reading the file HSSFWorkbook is for old excel format. use XSSFWorkbook instead
Edited:
copied from http://www.coderanch.com/t/463779/java/java/read-xlsx-sheet-Client-Side.
did u do the same thing?
try {
System.out.println("destDir==> "+destDir);
XSSFWorkbook workBook = new XSSFWorkbook(destDir);
XSSFSheet sheet = workBook.getSheetAt(0);
totalRows = sheet.getPhysicalNumberOfRows();
System.out.println("total no of rows >>>>"+totalRows);
} catch (IOException e) {
e.printStackTrace();
}
Edit 2:
Learn about apache POI from this link

Categories

Resources