package com.lietou.open.common.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.poifs.filesystem.POIFSFileSystem;
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 ExcelUtil
{
private static final String EXCEL_2007 = "xlsx";
public static void main(String[] args) throws Exception
{
String path = "D:\\学历.xlsx";
ExcelUtil.read(path);
}
public static void read(InputStream is, boolean flag) throws Exception
{
Workbook wb = null;
if(flag)
{
wb = new HSSFWorkbook(is);// 2003
}
else
{
wb = new XSSFWorkbook(is);// 2007
}
read(wb);
}
public static void read(String fileName) throws Exception
{
Workbook wb = null;
if(fileName.endsWith(EXCEL_2007))
{
wb = new XSSFWorkbook(fileName);
}
else
{
File f = new File(fileName);
FileInputStream is = new FileInputStream(f);
POIFSFileSystem fs = new POIFSFileSystem(is);
wb = new HSSFWorkbook(fs);
is.close();
}
read(wb);
}
public static void read(Workbook wb) throws Exception
{
try
{
for(int k = 0; k < wb.getNumberOfSheets(); k++)
{
// sheet
Sheet sheet = wb.getSheetAt(k);
int rows = sheet.getPhysicalNumberOfRows();
for(int r = 0; r < rows; r++)
{
// 定义 row
Row row = sheet.getRow(r);
if(row != null)
{
int cells = row.getPhysicalNumberOfCells();
for(short c = 0; c < cells; c++)
{
Cell cell = row.getCell(c);
if(cell != null)
{
Object value = null;
switch(cell.getCellType())
{
case Cell.CELL_TYPE_FORMULA:
value = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
if(HSSFDateUtil.isCellDateFormatted(cell))
{
value = cell.getDateCellValue();
}
else
{
value = cell.getNumericCellValue();
}
break;
case Cell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
cell.getDateCellValue();
break;
default:
}
System.out.println(value);
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
poi读取excel2003/2007
最新推荐文章于 2023-02-03 16:06:48 发布