Use Apache POI to read Excel(.xlsx)
Add:
'xmlbeans-2.x.x' and 'poi-ooxml-schemas-3.x-xxx' jar’s.
package com.p1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
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_Read {
public void readExcel (String filePath) {
InputStream ExcelToRead = null;
XSSFWorkbook wb = null;
try {
ExcelToRead = new FileInputStream(filePath);
wb = new XSSFWorkbook(ExcelToRead);
} catch (FileNotFoundException e) {
e.getMessage();
} catch (IOException e) {
e.getMessage();
}
XSSFSheet sh = wb.getSheet("Sheet1");
XSSFRow row;
XSSFCell cell;
//Run all the rows
Iterator rows = sh.rowIterator();
while (rows.hasNext()) {
row = (XSSFRow) rows.next();
//Run all the cell of row
Iterator cells = row.cellIterator();
while (cells.hasNext()) {
cell = (XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
System.out.print(cell.getStringCellValue() + " ");
} else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
System.out.print(cell.getNumericCellValue() + " ");
} else if (cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
System.out.print(cell.getBooleanCellValue() + " ");
}else if (cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA) {
System.out.print(cell.getCellFormula() + " ");
}else if (cell.getCellType() == XSSFCell.CELL_TYPE_ERROR) {
System.out.print(cell.getErrorCellString() + " ");
}
}
System.out.println();
try {
ExcelToRead.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Excel_Read excelRead = new Excel_Read();
excelRead.readExcel("D:\\Test.xlsx");
}
}
No comments:
Post a Comment