主要是要知道使用apache的包
import org.apache.commons.fileupload.FileItem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
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.ss.usermodel.WorkbookFactory;
FileItem item = (FileItem) obj;
List<String[]> dataList = ExcelUtil.readAllData(item.getInputStream(), 0);
// 解析代码开始
/**
* 取Excel所有数据,包含header
*
*/
@SuppressWarnings("unchecked")
public static List<String[]> readAllData(InputStream is, int sheetIndex) throws Exception {
Workbook wb = null;
try {
wb = WorkbookFactory.create(is);
List<String[]> dataList = new ArrayList<String[]>();
int columnNum = 0;
int startColNum = 0;
int endColNum = 0;
Sheet sheet = wb.getSheetAt(sheetIndex);
if (sheet.getRow(0) != null) {
startColNum = sheet.getRow(0).getFirstCellNum();
endColNum = sheet.getRow(0).getLastCellNum();
columnNum = endColNum - startColNum;
}
if (columnNum > 0) {
for (Row row : sheet) {
if (row == null) {
continue;
}
String[] singleRow = new String[columnNum + 1];
singleRow[0] = (row.getRowNum() + 1) + "";
for (int i = 0; i < columnNum; i++) {
Cell cell = row.getCell(i + startColNum);
if (cell != null) {
singleRow[i + 1] = getCellValue(cell);
} else {
singleRow[i + 1] = "";
}
}
dataList.add(singleRow);
}
}
return dataList;
} catch (IOException e) {
logger.error("io exception", e);
} finally {
try {
is.close();
} catch (IOException e) {
logger.error("io close error", e);
}
}
return Collections.EMPTY_LIST;
}
/**
* 取一个excel单元格的值
*/
public static String getCellValue(Cell cell) {
String cellValue = "";
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = StringUtil.trim(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = cell.getBooleanCellValue() ? "TRUE" : "FALSE";
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
} else {
cellValue = NumberFormat.getNumberInstance().format(cell.getNumericCellValue())
.replaceAll(",", "");
}
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = StringUtil.trim(cell.getCellFormula());
break;
case Cell.CELL_TYPE_ERROR:
cellValue = StringUtil.trim(String.valueOf(cell.getErrorCellValue()));
break;
default:
cellValue = "";
}
}
return cellValue;
}