import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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 PoiExcelUtil {
/**
* 获取Excel文件的内容
* @param in 文件流
* @param isXls xls 或 Xlsx
* @return
*/
public static List<String[]> readExcel(InputStream in, boolean isXls) {
List<String[]> list = new ArrayList<String[]>();
Workbook workbook = null;
try {
if (isXls) {
workbook = new HSSFWorkbook(in);//97-2003 Excel工作簿对象
} else {
workbook = new XSSFWorkbook(in);//2007 Excel工作簿对象
}
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
Sheet sheet = workbook.getSheetAt(i);//Excel工作表对象
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
if(j == 0){
continue;//跳过Header
}
Row row = sheet.getRow(j);//Excel工作表的行
String[] cellValues = new String[row.getLastCellNum()];
for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
Cell cell = row.getCell(k, Row.RETURN_BLANK_AS_NULL);//Excel工作表指定行的单元格
if(null == cell){
cellValues[k] = "";
}else{
//判断单元格值类型
switch(cell.getCellType()){
case Cell.CELL_TYPE_STRING://字符串类型
cellValues[k] = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC://数值类型
if(HSSFDateUtil.isCellDateFormatted(cell)){
cellValues[k] = cell.getDateCellValue().toString();
}else{
DecimalFormat decimalFormat = new DecimalFormat("#");
cellValues[k] = decimalFormat.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_FORMULA://公式
cellValues[k] = cell.getCellFormula();
break;
case Cell.CELL_TYPE_ERROR|Cell.CELL_TYPE_BLANK:
cellValues[k] = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValues[k] = String.valueOf(cell.getBooleanCellValue());
break;
default:
cellValues[k] = "";
}
}
}
list.add(cellValues);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
File file = new File("C:\\Users\\Administrator\\Desktop\\LOLO DATA\\majia20150515.xls");
boolean isXls = file.getName().endsWith(".xls")||file.getName().endsWith(".XLS");
InputStream in = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String[]> list = PoiExcelUtil.readExcel(in, isXls);
for(Object[] obj : list){
StringBuffer buffer = new StringBuffer();
for (Object object : obj) {
buffer.append(object).append(" ");
}
System.out.println(buffer.toString());
}
System.out.println("list size : " + list.size());
}
}
读取Excel内容的工具类PoiExcelUtil
最新推荐文章于 2024-08-24 03:49:49 发布