前端:
<li class="btn_uploads"><input type="file" id="wjsc" οnchange='importf()'><i class="Hui-iconfont"></i> 导入</li>
js:
//导入
function importf() {
var txt = document.getElementById("wjsc").value.substr(
document.getElementById("wjsc").value.lastIndexOf("."))
.toLowerCase();
if (txt != '.xls' && txt != '.xlsx') {
layer.alert("文件只能是xls文件或者是xlsx文件!!!");
this.value = "";
return false;
} else {
var formData = new FormData();
formData.append("file",$("#wjsc")[0].files[0]);
$.ajax({
url : "/addproduct/lead",
type : "post",
// 告诉jQuery不要去处理发送的数据
processData : false,
// 告诉jQuery不要去设置Content-Type请求头
contentType : false,
data:formData,
success : function(result) {
if(result.code=="1"){
layer.alert("导入成功")
$("#isbn").val(result.data)
}else{
layer.alert("导入失败")
}
}
});
}
controller
@RequestMapping(value = "/lead")
@ResponseBody
public Map<String, Object> readXlsx(@RequestParam("file") MultipartFile file) throws Exception {
try {
InputStream inputStream = file.getInputStream();
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
Workbook workbook = WorkbookFactory.create(poifsFileSystem);
Sheet hssfSheet = workbook.getSheetAt(0); // 示意访问sheet
StringBuilder isbns = new StringBuilder();
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
Row xssfRow = hssfSheet.getRow(rowNum);
int minColIx = xssfRow.getFirstCellNum();
int maxColIx = xssfRow.getLastCellNum();
for (int colIx = minColIx; colIx < maxColIx; colIx++) {
Cell cell = xssfRow.getCell(colIx);
if (cell == null) {
continue;
}
isbns = isbns.append(cell.toString() + ",");
}
}
String sb = isbns.toString().substring(0, isbns.toString().length() - 1);
return getResultObjectData(ResultCode.SUCCESS, sb, "成功获取导入信息!");
} catch (Exception e) {
return getResultObjectData(ResultCode.FAILED, null, "获取导入信息失败!");
}
}
pom.xml
<!-- excel表格处理 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>smtp</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>
效果: