首頁 > 軟體

Java利用Easyexcel匯出excel表格的範例程式碼

2022-07-15 18:02:04

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內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com