html:
1 <input class="import-btn" type="file" accept=".excel">
樣式:

script(前端):
$('.import-btn').change(function () {
var formData = new FormData(),
name = $(this).val()
formData.append('file', $(this)[0].files[0])
// 此處可傳入多個參數
formData.append('name', name)
$.ajax({
url: webRoot + '/deviceinfoup/export',
type: 'post',
async: false,
data: formData,
// 告訴jQuery不要去處理發送的數據
processData: false,
// 告訴jQuery不要去設置Content-Type請求頭
contentType: false,
beforeSend: function () {
console.log('正在進行,請稍候')
},
success: function (res) {
if (+res === '01') {
console.log('導入成功')
} else {
console.log('導入失敗')
}
}
})
})
后端代碼(springmvc):
@RequestMapping("/export")
public void export(VivoIMEIUp zipRequest,
@RequestParam("file") MultipartFile file,
HttpServletRequest request, HttpServletResponse response) {
try {
// @RequestParam("file") MultipartFile file 是用來接收前端傳遞過來的文件
// 1.創建workbook對象,讀取整個文檔
InputStream inputStream = file.getInputStream();
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
HSSFWorkbook wb = new HSSFWorkbook(poifsFileSystem);
// 2.讀取頁腳sheet
HSSFSheet sheetAt = wb.getSheetAt(0);
// 3.循環讀取某一行
for (Row row : sheetAt) {
// 4.讀取每一行的單元格
String stringCellValue = row.getCell(0).getStringCellValue(); // 第一列數據
String stringCellValue2 = row.getCell(1).getStringCellValue();// 第二列
// 寫多少個具體看大家上傳的文件有多少列.....
// 測試是否讀取到數據,及數據的正確性
System.out.println(stringCellValue);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
