前端代码:
<div class="form-group" id="thumbnailUploadContainer" class="col-sm-10" style="float: left; margin-right: 50px;">
<input id="articleImageFile" name="excelFile" type="file" class="form-control" style="width: 300px; display: inline;" />
<input id="saveZipButton" type="button" style="width: 60px;height: 35px;" value="上传" />
</div>
$("#saveZipButton").on('click', function() {
var formData = new FormData();
var name = $("#articleImageFile").val();
formData.append("file", $("#articleImageFile")[0].files[0]);
formData.append("name", name);//这个地方可以传递多个参数
$.ajax({
url: '${basePath}/electricMerchant/export',
type: 'POST',
async: false,
data: formData,
// 告诉jQuery不要去处理发送的数据
processData: false,
// 告诉jQuery不要去设置Content-Type请求头
contentType: false,
beforeSend: function () {
console.log("正在进行,请稍候");
},
success: function (responseStr) {
if (responseStr == "01") {
alert("导入成功");
} else {
alert("导入失败");
}
}
});
});
后端代码:
@RequestMapping("/export")
public void export(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
try {
// @RequestParam("file") MultipartFile file 是用来接收前端传递过来的文件
// 1.创建workbook对象,读取整个文档
InputStream inputStream = file.getInputStream();
//POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
// 2.读取页脚sheet
XSSFSheet sheetAt = wb.getSheetAt(0);
// 3.循环读取某一行
int index = 0;
for (Row row : sheetAt) {
// 4.读取每一行的单元格
if (index == 0) {
index++;
continue;
}
String stringCellValue = row.getCell(0).getStringCellValue(); // 第一列数据
String stringCellValue2 = row.getCell(1).getStringCellValue();// 第二列
String stringCellValue3 = row.getCell(2).getStringCellValue();// 第三列
String stringCellValue4 = row.getCell(3).getStringCellValue();// 第四列
row.getCell(4).setCellType(CellType.STRING);
String stringCellValue5 = row.getCell(4).getStringCellValue();// 第四列
// 写多少个具体看大家上传的文件有多少列.....
// 测试是否读取到数据,及数据的正确性
System.out.println(stringCellValue);
System.out.println(stringCellValue2);
System.out.println(stringCellValue3);
System.out.println(stringCellValue4);
System.out.println(stringCellValue5);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
可能遇到的问题:excel2003和excel2007版本的问题,解决办法如下:
(1)判断文件后缀名是xls,还是xlsx
(2)如果是xls,使用HSSFWorkbook;如果是xlsx,使用XSSFWorkbook