<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
还是使用poi-ooxml,可以解析xls和xlsx两种文件。
前台使用<input type="file"/>,form表单提交,
或者使用formData用ajax提交(注意$.ajax加上 processData: false,contentType: false两个属性),
注意form 的属性enctype="multipart/form-data"
然后后台用MultipartFile 的类来接受,基本上上传文件的都是用这个类,至于原因我也不是很清楚
拿到文件后接着生成workbook
public static Workbook readExcel(MultipartFile file) throws IOException {
Workbook wb = null;
String filePath = file.getOriginalFilename();
if(filePath.lastIndexOf(".") < 0)
return wb = null;
String extString = filePath.substring(filePath.lastIndexOf("."));
InputStream is = file.getInputStream();
if(".xls".equals(extString)){
return wb = new HSSFWorkbook(is);
}else if(".xlsx".equals(extString)){
return wb = new XSSFWorkbook(is);
}else{
return wb = null;
}
}
通过判断后缀名生成不同的Workbook
生成Workbook后就可以拿到表格的数据了
Workbook wb = ExcelUtils.readExcel(file);
Sheet sheet = wb.getSheetAt(0);//excel的分页
//获取最大行数
int rownum = sheet.getPhysicalNumberOfRows();
//获取第一行
Row row = sheet.getRow(0);
//获取最大列数
int colnum = row.getPhysicalNumberOfCells();
for (int i = 1; i<rownum; i++) {
row = sheet.getRow(i);
Cell cell = row.getCell(j);//拿到单元格
}
最终的目的就是拿到单元格的数据
拿到以后进行转化
public static Object getCellFormatValue(Cell cell) throws ParseException{
Object cellValue = null;
if(cell!=null){
//判断cell类型
switch(cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC:{
//判断cell是否为日期格式
if(DateUtil.isCellDateFormatted(cell)){
//转换为日期格式YYYY-mm-dd
Date date = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
cellValue = sdf.format(date);
}else{
cell.setCellType(Cell.CELL_TYPE_STRING);
cellValue = cell.getRichStringCellValue().getString();
//数字
//cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
}
case Cell.CELL_TYPE_FORMULA:{
cellValue = String.valueOf(cell.getNumericCellValue());
break;
}
case Cell.CELL_TYPE_STRING:{
cellValue = cell.getRichStringCellValue().getString();
break;
}
default:
cellValue = "";
}
}else{
cellValue = "";
}
return cellValue;
}
我是把时间格式和数字格式都转化成String类型,接着进行后期处理,因为数字类型会自动读取成double的类型,十分烦人,而时间格式有时候好使有时候不好使,会识别成String类型,所以我就统一转成String类型处理了。
完