package cn.com.gome.scot.alamein.business.report.common.util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ReadExcelUtils {
private Workbook wb;
private Sheet sheet;
private Row row;
public ReadExcelUtils() {}
public ReadExcelUtils(String filepath) {
if (filepath == null) {
return;
}
String ext = filepath.substring(filepath.lastIndexOf("."));
try {
InputStream is = new FileInputStream(filepath);
if (".xls".equals(ext)) {
wb = new HSSFWorkbook(is);
} else if (".xlsx".equals(ext)) {
wb = new XSSFWorkbook(is);
} else {
wb = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Map<Integer, Map<Integer, Object>> ReadExcelcontent(String filepath) {
Map<Integer, Map<Integer, Object>> map = null;
try {
ReadExcelUtils excelReader = new ReadExcelUtils(filepath);
map = excelReader.readExcelContent();
} catch (FileNotFoundException e) {
System.out.println("未找到指定路径的文件!");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public String[] readExcelTitle() throws Exception {
if (wb == null) {
throw new Exception("工作簿Workbook对象为空!");
}
sheet = wb.getSheetAt(0);
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
System.out.println("colNum:" + colNum);
String[] title = new String[colNum];
for (int i = 0; i < colNum; i++) {
title[i] = row.getCell(i).getCellFormula();
}
return title;
}
public Map<Integer, Map<Integer, Object>> readExcelContent() throws Exception {
if (wb == null) {
throw new Exception("工作簿Workbook对象为空!");
}
Map<Integer, Map<Integer, Object>> content = new HashMap<Integer, Map<Integer, Object>>();
sheet = wb.getSheetAt(0);
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
Map<Integer, Object> cellValue = new HashMap<Integer, Object>();
while (j < colNum) {
Object obj = getCellFormatValue(row.getCell(j));
cellValue.put(j, obj);
j++;
}
content.put(i, cellValue);
}
return content;
}
private Object getCellFormatValue(Cell cell) {
Object cellvalue = "";
if (cell != null) {
switch (cell.getCellTypeEnum()) {
case NUMERIC: {
cellvalue = (int) cell.getNumericCellValue();
break;
}
case FORMULA: {
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
cellvalue = date;
} else {
cellvalue = String.valueOf(cell.getNumericCellValue());
}
break;
}
case STRING:
cellvalue = cell.getRichStringCellValue().getString();
break;
default:// 默认的Cell值
cellvalue = "";
}
} else {
cellvalue = "";
}
return cellvalue;
}
}