第一次尝试Web项目上传Excel数据进行导入
如果有哪里做的不对不好或者有更好的方法请联系我,谢谢
pom.xml中添加
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
只是做了一个学习测试,所以并没有插入数据库
Controller的代码
@RequestMapping("/upload")
public String upload(@RequestParam("uploadFile") MultipartFile uploadFile) {
if (MultipartFileWaf.checkSize(uploadFile)) {
String excelType = MultipartFileWaf.checkIsExcel(uploadFile);
try {
InputStream fileInputStream = uploadFile.getInputStream();
if ("xls".equals(excelType)) {
HSSFWorkbook hwb = new HSSFWorkbook(fileInputStream);
HSSFSheet hsheet = hwb.getSheetAt(0);
medicalService.saveHSSFSheetMessage(hsheet);
hwb.close();
} else if ("xlsx".equals(excelType)) {
XSSFWorkbook xwb = new XSSFWorkbook(fileInputStream);
XSSFSheet xsheet = xwb.getSheetAt(0);
medicalService.saveXSSFSheetMessage(xsheet);
xwb.close();
} else {
System.out.println("上传失败");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("上传失败");
}
return "success";
}
检验文件大小的方法我就不发出来了,xls和xlsx的类不同,但是操作相同,一直在找这里有没有办法优化。
private DecimalFormat df = new DecimalFormat("0");
@Override
public int saveHSSFSheetMessage(HSSFSheet sheet) {
// TODO Auto-generated method stub
for(int i = 1;i <= sheet.getLastRowNum();i++) {
Row row = sheet.getRow(i);
Cell sid = row.getCell(0);
Cell sname = row.getCell(1);
Cell stature = row.getCell(2);
Cell bp = row.getCell(3);
Cell vision = row.getCell(4);
String cellText = "";
if("NUMERIC".equals(sid.getCellTypeEnum().toString())) {
cellText = df.format(sid.getNumericCellValue());
}
else {
cellText = sid.toString();
}
System.out.println(cellText+" "+sname+" "+stature+" "+bp+" "+vision+" ");
}
return 0;
}
@Override
public int saveXSSFSheetMessage(XSSFSheet sheet) {
// TODO Auto-generated method stub
for(int i = 1;i <= sheet.getLastRowNum();i++) {
Row row = sheet.getRow(i);
Cell sid = row.getCell(0);
Cell sname = row.getCell(1);
Cell stature = row.getCell(2);
Cell bp = row.getCell(3);
Cell vision = row.getCell(4);
String cellText = "";
if("NUMERIC".equals(sid.getCellTypeEnum().toString())) {
cellText = df.format(sid.getNumericCellValue());
}
else {
cellText = sid.toString();
}
System.out.println(cellText+" "+sname+" "+stature+" "+bp+" "+vision+" ");
}
return 0;
}
这里有个对excel数据类型的判定,POI3.15后就放弃getCellType进而使用getCellTypeEnum