EXCEL 表格

一、依赖
        
            org.apache.poi
            poi-ooxml
            4.0.1
        
二、导入
HTML结构,用表单接收上传的文件
-> 选择提交的文件
JavaScript脚本,封装上传到服务器的文件
        var $file = $("input[name=file]");
        var name = $file.val();
        var suffix = name.substring(name.lastIndexOf('.'));
        if (suffix == '.xls' || suffix == '.xlsx') {
            var data = new FormData();
            data.append("file", $file[0].files[0]);
            $.ajax({
                type: "POST",
                data: data,
                contentType: false,
                processData: false,
                mimeType: "multipart/form-data",
                url: "/import",
                success: function () {},
            });
        } else {
            console.log("不是EXCEL文件");
        }
服务器端接收前端传过来的文件
    @PostMapping("/import")
    @ResponseBody
    public boolean important(MultipartFile file) throws Exception {
        String name = file.getOriginalFilename();
        String suffix = name.substring(name.lastIndexOf("."));
        if (suffix.equalsIgnoreCase(".xls")) { -> 2003版本
            POIFSFileSystem system = new POIFSFileSystem(file.getInputStream());
            HSSFWorkbook workbook = new HSSFWorkbook(system);
            HSSFSheet sheet = workbook.getSheetAt(0);
            int rows = sheet.getLastRowNum();
            for (int i = 1; i <= rows; i++) {
                HSSFRow row = sheet.getRow(i);
                int columns = row.getLastCellNum();
                for (int j = 0; j < columns; j++) {
                    HSSFCell cell = row.getCell(j);
                    cell.setCellType(CellType.STRING);
                    String content = cell.getStringCellValue();
                    System.out.println(i + " " + j + " " + content);
                }
            }
        } else if (suffix.equalsIgnoreCase(".xlsx")) { -> 2007版本
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = workbook.getSheetAt(0);
            int rows = sheet.getLastRowNum();
            for (int i = 1; i <= rows; i++) {
                XSSFRow row = sheet.getRow(i);
                int columns = row.getLastCellNum();
                for (int j = 0; j < columns; j++) {
                    XSSFCell cell = row.getCell(j);
                    String content = cell.getRawValue();
                    System.out.println(i + " " + j + " " + content);
                }
            }
        } else {
            return false;
        }
        return true;
    }
三、导出
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @ResponseBody
    public boolean export(HttpServletResponse response) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook(); -> EXCEL的文档对象
        HSSFSheet sheet = workbook.createSheet("sheet"); -> EXCEL的工作簿
        HSSFCellStyle cellStyle = workbook.createCellStyle(); -> EXCEL的单元格样式
        cellStyle.setAlignment(HorizontalAlignment.CENTER); -> 设置水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); -> 设置垂直居中
        HSSFFont font = workbook.createFont(); -> 单元格字体
        font.setColor(HSSFFont.COLOR_RED);
        cellStyle.setFont(font);
        for (int i = 0; i < 10; i++) {
            HSSFRow row = sheet.createRow(i); -> EXCEL的行
            for (int j = 0; j < 10; j++) {
                HSSFCell cell = row.createCell(j); -> EXCEL的行的单元格
                cell.setCellValue(i + " " + j); -> 设置单元格里的值
                cell.setCellType(CellType.STRING); -> 设置单元格内容格式
                cell.setCellStyle(cellStyle); -> 设置单元格样式
            }
            sheet.setColumnWidth(i, 256 * 10); -> 设置表单列宽
        }
        String name = URLEncoder.encode("EXCEL表格", "UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8"); -> 客户端输出流
        response.setHeader("Content-disposition", "attachment;filename=" + name + ".xls"); -> 激活文件下载框
        response.setContentType("application/ms-excel"); -> 导出EXCEL类型
        OutputStream stream = response.getOutputStream();
        workbook.write(stream);
        workbook.close();
        return true;
    }
var $thead = $("#bootstrap-table thead div[class=th-inner]"); -> 表头
var $tbody = $("#bootstrap-table tbody tr"); -> 表列
var application = "application/vnd.ms-excel"; -> xls文件格式

var excel = '' + '';
for (var i = 0; i < $thead.length; i++) {
  excel += '';
}
excel += '';
for (var i = 0; i < $tbody.length; i++) {
  excel += '';
  var $td = $tbody.eq(i).find('td:not(:has( > div))');
  for (var j = 0; j < $td.length; j++) {
    excel += '';
    }
  excel += '';
}
excel += '
' + $thead.eq(i).text() + '
' + $td.eq(j).text() + '
'; var excelFile = ''; excelFile += ''; excelFile += ''; excelFile += ''; excelFile += ''; excelFile += ''; excelFile += excel; excelFile += ''; excelFile += ''; var uri = 'data:' + application + ';charset=utf-8,' + encodeURIComponent(excelFile); var link = document.createElement('a'); link.href = uri; $(link).css("visibility", "hidden"); $(link).attr("download", '模板.xls'); document.body.appendChild(link); link.click(); document.body.removeChild(link);
OFFICE MIME Type
.doc application/msword
.dot application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm application/vnd.ms-word.document.macroEnabled.12
.dotm application/vnd.ms-word.template.macroEnabled.12
.xls application/vnd.ms-excel
.xlt application/vnd.ms-excel
.xla application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm application/vnd.ms-excel.sheet.macroEnabled.12
.xltm application/vnd.ms-excel.template.macroEnabled.12
.xlam application/vnd.ms-excel.addin.macroEnabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12
.ppt application/vnd.ms-powerpoint
.pot application/vnd.ms-powerpoint
.pps application/vnd.ms-powerpoint
.ppa application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm application/vnd.ms-powerpoint.presentation.macroEnabled.12
.ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12
四、下载模板
try { -> 请求后端接口
  InputStream inputStream = (InputStream) this.getClass()
  .getClassLoader().getResourceAsStream("mould.xlsx");
  response.setContentType("application/zip");
  OutputStream out = response.getOutputStream();
  response.setHeader("Content-Disposition","attachment;filename=mould.xlsx");
  int b = 0;
  byte[] buffer = new byte[1000000];
  while (b != -1) {
    b = inputStream.read(buffer);
    if(b!=-1) out.write(buffer, 0, b);
  }
  inputStream.close();
  out.close();
  out.flush();
  } catch (IOException e) {
    e.printStackTrace();
}
文件存放位置(SpringBoot):resource/mould.xlsx

点击下载模板 -> 前端访问文件位置

你可能感兴趣的:(EXCEL 表格)