Reading Excel Rows and Columns - java

The code below is to read a large excel file. I got an "Cannot get a text value from a numeric cell at org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch" error. How do I fix this. Column 1 is Numerical Value, Column 2 is String Value.
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.Vector;
public class ReadExcel {
public static void main(String[] args) throws Exception {
String filename = "C:/Documents and Settings/oemiola/My Documents/Defects_Input.xls";
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator rowIter = sheet.rowIterator();
while(rowIter.hasNext()){
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector<String> cellStoreVector=new Vector<String>();
while(cellIter.hasNext()){
HSSFCell myCell = (HSSFCell) cellIter.next();
String cellvalue = myCell.getStringCellValue();
cellStoreVector.addElement(cellvalue);
}
String firstcolumnValue = null;
String secondcolumnValue = null;
int i = 0;
firstcolumnValue = cellStoreVector.get(i).toString();
secondcolumnValue = cellStoreVector.get(i+1).toString();
insertQuery(firstcolumnValue,secondcolumnValue);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
}
private static void insertQuery(String firstcolumnvalue,String secondcolumnvalue) {
System.out.println(firstcolumnvalue + " " +secondcolumnvalue);
}
}

Use Cell#getCellType to determine whether there is a number or a string in the cell. If it's numeric, then use getNumericCellValue instead of getStringCellValue.

Related

Read data from Excel and write to Docx file using java

I have some records with header in my excel sheet.I want to read all the records and write to the docx file along with header using java.Thanks for the helps.
Able to write one excel to other excel file but failed to write in docx file.
I have try this way but the word file is generated as corrupted.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
public class ExcelReaderDemo {
public static final String SAMPLE_XLSX_FILE_PATH =
"C:/XLXSToDocx/Roaster.xlsm";
public static final String FILE_PATH ="C:/XLXSToDocx/writeExcel.docx";
public static void main(String[] args) throws IOException,
InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new
File(SAMPLE_XLSX_FILE_PATH));
System.out.println("Workbook has " + workbook.getNumberOfSheets() + "
Sheets : ");
Sheet sheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
try {
FileOutputStream fos = new FileOutputStream(FILE_PATH);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println();
}
workbook.close();
}
}
I would suggest to use Apache Poi lib (https://poi.apache.org/)
Rewrite your code like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelReaderDemo {
public static final String SAMPLE_XLSX_FILE_PATH = "C:/XLXSToDocx/Roaster.xlsm";
public static final String FILE_PATH = "C:/XLXSToDocx/writeExcel.docx";
public static void main(String[] args) throws IOException, InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
try {
FileOutputStream fos = new FileOutputStream(FILE_PATH);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DONE !!!");
}
}

i want to get&set the value in excel .xls file and get the error message from application

i want to get the (valid and invalid) data from excel .xls file and apply that in my application login page.when the error message is display.i want to write failed in excel file.from my code, i can get the value from excel and apply it in my application but cant write the output in excel.i attached my code here.anyone please help me to fix this.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
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;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class exceltowrite {
public FileInputStream fis = null;
public FileOutputStream fos = null;
public HSSFWorkbook workbook = null;
public HSSFSheet sheet = null;
public HSSFRow row = null;
public HSSFCell cell = null;
String xlFilePath;
public exceltowrite(String string, String xlFilePath) throws IOException {
this.xlFilePath = xlFilePath;
fis = new FileInputStream(xlFilePath);
workbook = new HSSFWorkbook(fis);
fis.close();
}
public static void main(String[]args) throws EncryptedDocumentException, InvalidFormatException, IOException, InterruptedException {
for(int i=1;i<=29;i++) {
String u1 =exceltowrite.getdata(i,0);
String p1=exceltowrite.getdata(i,1);
WebDriver d1=new FirefoxDriver();
d1.get("http:\\www.google.com");
d1.get("napplication site");
d1.findElement(By.name("AdminLoginForm[email]")).sendKeys(u1);
d1.findElement(By.name("AdminLoginForm[password]")).sendKeys(p1);
d1.findElement(By.name("login-button")).click();
Thread.sleep(2000);
WebElement e1= d1.findElement(By.xpath("email error message path"));
String s1=e1.getText();
WebElement e2=d1.findElement(By.xpath("password error message path"));
String s2=e2.getText();
if(s1.equals("Email cannot be blank.")) {
System.out.println("emailid failed");
d1.quit();
if(s2.equals("Password cannot be blank.")) {
System.out.println("password failed");
d1.quit();
} else {
System.out.println("password pass");
d1.quit();
}
} else {
d1.quit();
}
}
}
public static String getdata(int i, int j) throws EncryptedDocumentException, InvalidFormatException, IOException {
FileInputStream fis=new FileInputStream("file path");
Workbook wb=WorkbookFactory.create(fis);
String s=wb.getSheet("Sheet1").getRow(i).getCell(j).getStringCellValue();
return s;
}
public boolean setCellData(String sheetName, int colNumber, int rowNum, String value)
{
try
{
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(rowNum);
System.out.println(row);
cell = row.getCell(colNumber);
System.out.println(cell);
cell.setCellValue(value);
fos = new FileOutputStream(xlFilePath);
workbook.write(fos);
fos.close();
System.out.println("Finished");
}
catch (Exception ex)
{
ex.printStackTrace();
return false;
}
return true;
}}
}
my another class is this
public class Demo {
public static void main(String args[]) throws Exception
{
// exceltowrite at=new exceltowrite("file path");
for(int j=0;j<=29;j++){
at.setCellData("Sheet1",2,j,"failed");
}}}
public static void write() throws IOException {
String home = System.getProperty("user.home");
String downlpad = home + "\\Downloads";
File file = new File(downlpad + "\\" + "Suhit-File-to-Download.xlsx");
FileOutputStream outputStream = new FileOutputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Java Books");
ArrayList<Object> bookData = new ArrayList<>();
bookData.add("Name");
bookData.add("Address");
bookData.add("Number");
XSSFRow row = sheet.createRow(0);
for (int i = 0; i < bookData.size(); i++) {
XSSFCell cell3 = row.createCell(i);
cell3.setCellValue((String) bookData.get(i));
}
workbook.write(outputStream);
workbook.close();
}

Java arraylist how to read DDE double values from an excel file and write into an array?

I have an excel file with DDE links to external sources. I am trying to read those values into my java application.
I am using Apache POI library to read the excel. When trying, I get the following error:
Exception in thread "main" java.lang.IllegalStateException: Cannot get a numeric value from a text cell
at org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch(HSSFCell.java:643)
at org.apache.poi.hssf.usermodel.HSSFCell.getNumericCellValue(HSSFCell.java:668)
at BasketExcelRead.run(BasketExcelRead.java:40)
at Tester.main(Tester.java:7)
My code is
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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 BasketExcelRead implements Runnable {
public void run() {
String inputFile = "someexcel.xls";
List<String> code = new ArrayList<String>();
List<Double> bid = new ArrayList<Double>();
List<Double> share = new ArrayList<Double>();
try {
FileInputStream file = new FileInputStream(new File(inputFile));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
int ss = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < ss; i++) {
HSSFRow row = sheet.getRow(i);
HSSFCell cellCode = row.getCell(0);
HSSFCell cellBid = row.getCell(7);
HSSFCell cellShare = row.getCell(9);
code.add(cellCode.getStringCellValue());
bid.add(cellBid.getNumericCellValue());
share.add(cellShare.getNumericCellValue());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("done reading");
}
for (int i = 0; i < 30; i++) {
System.out.println(code.get(i)+" "+bid.get(i)+" "+share.get(i));
}
}
}
The cell that text/numeric value conflict happens at bid.add(cellBid.getNumericCellValue());
This cellBid is the DDE link within the excel file which shows some numeric values

Generating files by reading excel sheet

There is a excel file which is having lot of file names in one of its column . I need to write a java code that should read those file names and generate the same in destination.Can any one help me ?
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
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.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) throws IOException {
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t\t");
FileOutputStream outFile =new FileOutputStream(new File("C:\\"+cell.getStringCellValue()));
workbook.write(outFile);
}
System.out.println("");
}
file.close();
/* FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);*/
//outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There are some libraries you can use to read excel files. In my case, I chose the Apache POI which you can download for free and then add to your project. Once you added it, create your Document:
HSSFWorkbook workbook = new HSSFWorkbook( new FileInputStream("filename.xls") );
or, if it's an excel document from 2007 or later:
XSSFWorkbook workbook = new XSSFWorkbook( new FileInputStream("filename.xlsx") );
Now you can iterate through each row and read out the first column:
for( Row row : workbook.getSheetAt(0) ) // Go through each row in sheet 0
System.out.println( row.getCell(0).getStringCellValue() );
public class Test {
public static void main(String[] args) throws IOException {
try {
FileInputStream file = new FileInputStream(new File("D:\\sampleFileNames.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
FileOutputStream outFile= null;
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
Cell cell = cellIterator.next();
File file1 = new File("D:\\Ganesh\\"+cell.getStringCellValue().toString());
if(!file1.createNewFile()) {
System.out.println("File already exists");
/* Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t\t");
outFile =new FileOutputStream(new File("D:\\Ganesh\\"+cell.getStringCellValue().toString()));
//workbook.write(outFile);
System.out.println("");
}
file.close();
outFile.close();
/* FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);*/
//outFile.close();
}
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Poi Formula evaluation Error

I am using poi-3.8-20120326.jar and Excel 2007, trying to collect all the cell value in one list.
I am using formula for date increment operation. For example: =(i2+3) for k2 cell.
While evaluating this formula through my java code returns #VALUE! (i2 is a date cell.)
Without source it's hard to guess what's wrong, but I think that are two things that you may forget.
1) FormulaEvaluator
2) DataFormatter
Take a look at example.
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
public class CellReader {
private Workbook workbook;
private DataFormatter formatter;
private FormulaEvaluator evaluator;
private void openWorkbook(String file) throws FileNotFoundException,
IOException, InvalidFormatException {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
workbook = WorkbookFactory.create(fis);
evaluator = workbook.getCreationHelper().createFormulaEvaluator();
formatter = new DataFormatter(true);
} finally {
if (fis != null) {
fis.close();
}
}
}
private void printXLSX() {
Sheet sheet = null;
Row row = null;
Cell cell = null;
int lastRowNum;
int lastCellNum;
sheet = workbook.getSheetAt(0);
lastRowNum = sheet.getLastRowNum();
for (int j = 0; j <= lastRowNum; j++) {
row = sheet.getRow(j);
if (row == null) {
continue;
}
lastCellNum = row.getLastCellNum();
for (int k = 0; k <= lastCellNum; k++) {
cell = row.getCell(k);
if (cell == null) {
continue;
}
if (cell.getCellType() != Cell.CELL_TYPE_FORMULA) {
System.out.println(formatter.formatCellValue(cell));
} else {
System.out.println(formatter.formatCellValue(cell,evaluator));
}
}
}
}
public static void main(String[] args) {
CellReader converter = null;
try {
converter = new CellReader();
converter.openWorkbook("a.xlsx");
converter.printXLSX();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Categories

Resources