springboot + poi导出(excel)表格,支持中文自适应列宽

前言

优化springboot+poi导出excel表格,支持中文自适应的工具类.

工具类

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

public class ExportEncodeUtil {
    public static void HeaderCode(HttpServletRequest request, HttpServletResponse response, String sheetName, HSSFWorkbook wb) throws IOException {
        // 针对IE或者以IE为内核的浏览器:
        String userAgent = request.getHeader("User-Agent").toLowerCase();
        String fileName = sheetName + ".xlsx";
        if (userAgent.contains("msie") || userAgent.contains("trident")) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            // 非IE浏览器的处理:
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("success", "true");
        OutputStream os = response.getOutputStream();
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);//默认Excel名称

        wb.write(os);
        os.flush();
        os.close();
    }

    /**
     * 自适应宽度(中文支持)
     *  @param sheet
     * @param size
     */
    public static void setSizeColumn(HSSFSheet sheet, int size) {
        for (int columnNum = 0; columnNum < size; columnNum++) {
            int columnWidth = sheet.getColumnWidth(columnNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }

                if (currentRow.getCell(columnNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(columnNum);
                    if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            sheet.setColumnWidth(columnNum, columnWidth * 256);
        }
    }
}

service层关键代码

/**
     * 导出excel表格
     *  get方法
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public String export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Company> companies = companyRepository.findAll();
        HSSFWorkbook wb = new HSSFWorkbook();//创建Excel文件
        HSSFSheet sheet = wb.createSheet("企业信息表");
        String sheetName = sheet.getSheetName();
        wb.setSheetName(0, sheetName);
        sheet.setDefaultRowHeight((short) (20 * 20));
        CellStyle style = wb.createCellStyle();
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("企业名称");//为第一个单元格设值
        row.createCell(1).setCellValue("社会信用代码");//为第二个单元格设值
        row.createCell(2).setCellValue("联系人");//为第三个单元格设值
        row.createCell(3).setCellValue("联系电话");//为第三个单元格设值
        row.createCell(4).setCellValue("法人");//为第三个单元格设值
        row.createCell(5).setCellValue("地址");
        row.createCell(6).setCellValue("行业");
        row.createCell(7).setCellValue("创建日期");
        row.createCell(8).setCellValue("开业日期");
        row.createCell(9).setCellValue("员工数");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (companies != null && companies.size() > 0) {
            int i = 0;
            for (Company company : companies) {
                i++;
                row = sheet.createRow(i);
                row.createCell(0).setCellValue(company.getName());
                row.createCell(1).setCellValue(company.getCreditCode());
                row.createCell(2).setCellValue(company.getContactName());
                row.createCell(3).setCellValue(company.getContactPhone());
                row.createCell(4).setCellValue(company.getCorporation());
                row.createCell(5).setCellValue(company.getAddress());
                row.createCell(6).setCellValue(company.getIndustryName());

                String establishedDate = company.getEstablishedDate() != null ? sdf.format(company.getEstablishedDate()) : "";
                row.createCell(7).setCellValue(establishedDate);
                String openedDate = company.getOpenedDate() != null ? sdf.format(company.getOpenedDate()) : "";
                row.createCell(8).setCellValue(openedDate);
                Integer staffNum = company.getStaffNum() == null ? 0 : company.getStaffNum();
                row.createCell(9).setCellValue(staffNum);
            }
        }

         ExportEncodeUtil.setSizeColumn(sheet, companies .size());
        ExportEncodeUtil.HeaderCode(request, response, sheetName, wb);
        return "导出企业信息成功";
    }

你可能感兴趣的:(文件导入导出上传下载)