亲宝软件园·资讯

展开

Java Easyexcel导出excel

羁客% 人气:0

1.导入 EasyExcel Maven包

<!--easyexcel 导出excel依赖-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>2.2.7</version>
</dependency>

2.配置

配置表格表头样式,以及内容的写入方式

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.*;
 
import java.util.List;
 
 
public class EasyExcelWriteHandler implements SheetWriteHandler {
 
    /**
     * 表头数据
     */
    private final List<String> headsDatas;
 
    /**
     * 内容数据
     */
    private final List<List<String>> bodyDatas;
 
    /**
     * 表头样式
     */
    private CellStyle cellStyle;
 
    /**
     * 内容样式
     */
    private CellStyle cellStyleHeader;
 
 
    public EasyExcelWriteHandler(List<String> headsDatas, List<List<String>> bodyDatas) {
        this.headsDatas = headsDatas;
        this.bodyDatas = bodyDatas;
    }
 
 
    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
 
    }
 
    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Workbook workbook = writeWorkbookHolder.getWorkbook();
        Sheet sheet = workbook.getSheetAt(0);
 
        // 表头样式
        if (cellStyleHeader == null) {
            cellStyleHeader = workbook.createCellStyle();
            cellStyleHeader.setAlignment(HorizontalAlignment.CENTER);
            cellStyleHeader.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyleHeader.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            Font font = workbook.createFont();
            // 字体大小
            font.setFontHeightInPoints((short) 16);
            // 字体
            font.setFontName("微软雅黑");
            //加粗
            font.setBold(true);
            cellStyleHeader.setFont(font);
        }
 
        // 内容样式
        if (cellStyle == null) {
            cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            Font font = workbook.createFont();
            font.setFontName("微软雅黑");
            font.setFontHeightInPoints((short) 12);
            cellStyle.setFont(font);
        }
 
        //表头内容
        Row row = sheet.getRow(0);
        if (row == null) {
            row = sheet.createRow(0);
        }
        //遍历写入表头
        for (int rowInt = 0; rowInt < headsDatas.size(); rowInt++) {
            //获取列内容
            String cellValue = headsDatas.get(rowInt);
            //根据表头内容设置表头列宽(自适应表头宽度)
            sheet.setColumnWidth(rowInt, cellValue.length() * 875);
            Cell cell = row.getCell(rowInt);
            if (cell == null) {
                cell = row.createCell(rowInt);
            }
            cell.setCellStyle(cellStyleHeader);
            cell.setCellValue(cellValue);
 
            //遍历写入内容
            if (rowInt < bodyDatas.size()) {
                for (int bodyRowInt = 0; bodyRowInt < bodyDatas.get(rowInt).size(); bodyRowInt++) {
                    Row row0 = sheet.getRow(bodyRowInt + 1);
                    if (row0 == null) {
                        row0 = sheet.createRow(bodyRowInt + 1);
                    }
                    Cell cell0 = row0.getCell(rowInt);
                    if (cell0 == null) {
                        cell0 = row0.createCell(rowInt);
                    }
                    cell0.setCellStyle(cellStyle);
                    cell0.setCellValue(bodyDatas.get(rowInt).get(bodyRowInt));
                }
            }
        }
    }
}

3.输出Excel到前端

  public static void easyUtil1(ExcelBody excelBody) throws IOException {
       //转换内容数据
       List<List<String>> list2 = new ArrayList<>();
        for (List<Object> objects : excelBody.getBodyDatas()) {
            List<String> strs = new ArrayList<>();
            for (Object object : objects) {
                strs.add(String.valueOf(object));
            }
            list2.add(strs);
        }
        //设置表名
        String simpleDateFormat = new String((new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())).getBytes(), "UTF-8");
        //设置字符编码
        response.setCharacterEncoding("utf-8");
        //设置内容类型
        response.setContentType("application/vnd.ms-excel");
        //设置标题
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelBody.getFileName() + simpleDateFormat + ".xlsx", "utf-8"));
        //核心代码
        //方式一:
       //EasyExcel.write(response.getOutputStream()).head(list2).sheet("sheet1").doWrite(list2);
        //方式二:
        ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream());
        writerBuilder.registerWriteHandler(new EasyExcelWriteHandler(excelBody.getHeads(), list2));
        ExcelWriter excelWriter = writerBuilder.build();
        ExcelWriterSheetBuilder writerSheetBuilder = EasyExcel.writerSheet("Sheet1");
        excelWriter.write(new ArrayList<>(), writerSheetBuilder.build());
        excelWriter.finish();
    }
@Data
public class ExcelBody {
 
    /**
     * 文件名
     */
    private String fileName;
 
    /**
     * 表头
     */
    private List<String> heads;
 
    /**
     * 数据体
     */
    private List<List<Object>> bodyDatas;
}

加载全部内容

相关教程
猜你喜欢
用户评论