POI 设置某一列单元格格式

2,268 阅读1分钟
    @GetMapping("/downExcelFile")
    public void test(HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + "test.xlsx");
            response.setContentType("application/vnd.ms-excel");
            Workbook workbook = new SXSSFWorkbook();
            CellStyle cellStyle = workbook.createCellStyle();
            DataFormat dataFormat = workbook.createDataFormat();
            short format = dataFormat.getFormat("@");
//            int builtinFormat = BuiltinFormats.getBuiltinFormat("@");
//            cellStyle.setDataFormat((short) builtinFormat);
            cellStyle.setDataFormat(format);
            Sheet sheet = workbook.createSheet("计划模板");
            for (int i = 0; i < 1000; i++) {
                Row row = sheet.createRow(i);
                for (int j = 0; j < 10; j++) {
                    Cell cell = row.createCell(j);
                    // 若不设置,则删除该单元格数据后,再次写入数据TEXT格式展示
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue(i + "" + j);
                }
            }
            // POI will only apply this style to new cells added to the sheet.
            // 若不设置,则新增行数据不会TEXT的格式展示数据
            sheet.setDefaultColumnStyle(0, cellStyle);
            outputStream = new BufferedOutputStream(response.getOutputStream());
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }