Java利用Easyexcel导出excel表格的示例代码

2022-11-13 12:11:07 示例 导出 表格

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;
}

到此这篇关于Java利用Easyexcel导出excel表格的示例代码的文章就介绍到这了,更多相关Java Easyexcel导出excel内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章