POI解析Excel
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
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;
* 获取Execl的表头
* @param is
* @return
* @throws IOException
*/
public static List<String> ExcelHead(InputStream is) throws IOException{
List<String> head = new ArrayList<>();
POIFSFileSystem fs = new POIFSFileSystem(is);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
for (int i = 0; i < colNum; i++) {
HSSFCell cell = row.getCell(i);
head.add(cell.getStringCellValue());
}
return head;
}
/**
* 判断单元格内容的类型
* @param cell
* @return
*/
public String getCellValue(HSSFCell cell){
String result = null;
int cellType = cell.getCellType();
if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
result = formater.format(date);
} else {
result = new Double(cell.getNumericCellValue()).toString();
}
} else if (cellType == HSSFCell.CELL_TYPE_STRING) {
if (cell.getStringCellValue().trim().equals("")) {
result = null;
} else {
result = cell.getStringCellValue();
}
} else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
if (cell.getBooleanCellValue()) {
result = "true";
} else {
result = "false";
}
} else if (cellType == HSSFCell.CELL_TYPE_ERROR) {
result = null;
} else {
result = null;
}
return result;
}
/**
* 获取内容
* @param is
* @return
* @throws IOException
*/
public Map<Integer, String> ExcelBody(InputStream is) throws IOException {
Map<Integer, String> content = new HashMap<>();
String str = " ";
POIFSFileSystem fs = new POIFSFileSystem(is);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
int rowNum = sheet.getLastRowNum();
int colNum = row.getPhysicalNumberOfCells();
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
for (int j = 0; j < colNum; j++) {
str += getCellValue(row.getCell(j));
}
content.put(i, str);
str = " ";
}
return content;
}