首先导入maven依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13</version>
</dependency>
使用ajax上传excel文件:
<form id= "uploadForm">
<p >上传文件: <input type="file" name="file"/></ p>
<input type="button" value="上传" onclick="doUpload()" />
</form>
<script type="text/javascript">
function doUpload() {
var formData = new FormData($( "#uploadForm" )[0]);
$.ajax({
url: basePath+"page/excel",
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (result) {
console.log(result);
},
error: function (returndata) {
alert(returndata);
}
});
}
</script>
Java核心代码
@SuppressWarnings("resource")
@ResponseBody
@RequestMapping(value="/excel")
public Map<String,Object> excel(MultipartFile file) {
Map<String,Object> resultMap = new HashMap<>();
Workbook excel = null;
InputStream is = null;
try {
is = file.getInputStream();
excel = new XSSFWorkbook(is); //处理Excel2007
} catch (Exception ex) {
try {
excel = new HSSFWorkbook(is); //处理Excel2003以前版本
} catch (IOException e) {
e.printStackTrace();
}
}
// 循环工作表Sheet
for (int numSheet = 0; numSheet < excel.getNumberOfSheets(); numSheet++) {
Sheet sheet = excel.getSheetAt(numSheet);
if (sheet == null)
continue;
// 循环行Row(每一列),从第行开始
for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
if (row == null)
continue;
Cell cell0 = row.getCell(0); //第一列
if (cell0 == null)
continue;
System.out.println(cell0.getStringCellValue());
Cell cell1 = row.getCell(1); //第二列
if (cell1 == null)
continue;
System.out.println(cell1.getNumericCellValue());
}
}
resultMap.put("state", "success");
return resultMap;
}