前端Excel表格导入 并传给后端

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();
        }
 
    }
}
原文地址:https://www.cnblogs.com/cq-0715/p/9620764.html