备注:接上篇点击打开链接
1、controller层方法:
<span style="white-space:pre"> </span>@RequestMapping(value = "uploadFile")
public void uploadFile(Model model, MultipartFile file) throws Exception {
bluetoothService.uploadFileToDatabase(file);
model.addAttribute(new Protocol());
}
2、service实现层方法:
<span style="white-space:pre"> </span>public void uploadFileToDatabase(MultipartFile file) {
// TODO Auto-generated method stub
if (file == null) {
throw new BusinessException(ResponseCode.FAIL.code, "文件为空!");
}
String fileName = file.getOriginalFilename();
if (!(fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))) {
logger.error("文件{}格式不对,仅支持Excel文件!", fileName);
throw new BusinessException(ResponseCode.FAIL.code, "文件格式不对,仅支持Excel文件!");
}
XSSFWorkbook workBook = null;
try {
InputStream input = file.getInputStream();
workBook = new XSSFWorkbook(input);
} catch (Exception e) {
e.printStackTrace();
logger.error("===>>文件" + fileName + "异常:" + e.getMessage(), e);
throw new BusinessException(ResponseCode.FAIL.code, "文件上传异常:" + e.getMessage());
}
XSSFSheet sheet = workBook.getSheetAt(0);
if (sheet != null) {
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 1; i < rows; i++) {
XSSFRow row = sheet.getRow(i);
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
XSSFCell cell = row.getCell(j);
String cellStr = "";
if (cell != null) {
cellStr = cell.toString();
}
System.out.print("【" + cellStr + "】 ");
}
System.out.println();
}
}
}
注意:spring配置文件:applicationContext.xml增加配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定所上传文件的总大小不能超过800KB......注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="80000000"/>
</bean>