Hutool 導出簡單Excel


導出Excel預覽

1.准備環境

        <!-- 為了驗證hutool中的方法,導入包進行對比 -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.5</version>
        </dependency>
//測試接口導出
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
//poi包
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
//測試包
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
//lombok
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2.Demo

package com.example.demo.excel;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * @author pengyifeng
 * @version 2.0
 * @ClassName ExcelUser.java
 * @Description 導出類
 * @createTime 2021年11月15日 10:54:00
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExcelUser {
    private String name;
    private String age;
    private Date birthDay;
}

package com.example.demo.excel;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author pengyifeng
 * @version 2.0
 * @ClassName excelDemo.java
 * @Description 基礎excel導出
 * @createTime 2021年11月15日 10:49:00
 */
//瀏覽器請求下載解除注釋
//@RestController
public class ExcelDemo {
    //@RequestMapping("/export")
    //void export(HttpServletResponse response) throws FileNotFoundException {
    @Test
    public void export() throws FileNotFoundException {
        List list = new ArrayList<>();
        list.add(new ExcelUser("zhangsan", "1231", new Date()));
        list.add(new ExcelUser("zhangsan1", "1232", new Date()));
        list.add(new ExcelUser("zhangsan2", "1233", new Date()));
        list.add(new ExcelUser("zhangsan3", "1234", new Date()));
        list.add(new ExcelUser("zhangsan4", "1235", new Date()));
        list.add(new ExcelUser("zhangsan5", "1236", DateUtil.date(new Date())));
        // 通過工具類創建writer,默認創建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        // 自定義標題別名
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("age", "年齡");
        writer.addHeaderAlias("birthDay", "生日");
        // 合並單元格后的標題行,使用默認標題樣式
        writer.merge(2, "申請人員信息");
        //設置默認高度
        writer.setDefaultRowHeight(30);
        // 一次性寫出內容,使用默認樣式,強制輸出標題
        writer.write(list, true);
        //自適應列寬(必須放在writer.write(list, true)寫入后)
        ExcelUtils.setSizeColumn(writer.getSheet(),6);

        //瀏覽器導出
        //ExcelUtils.downloadExcel(response,"excelDemo",writer);

        //本地測試下載
        FileOutputStream outputStream = new FileOutputStream("D:/home/excel/excelDemo.xlsx");
        writer.flush(outputStream, true);
        writer.close();
    }
}

package com.honghe.hours.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author pengyifeng
 * @version 2.0
 * @ClassName ExcelUtils.java
 * @Description TODO
 * @createTime 2021年11月03日 16:48:00
 */
@Slf4j
public class ExcelUtils {
    /**
     * 方法描述: 下載excel文件
     *
     * @param response 響應
     * @param fileName 文件名稱
     * @param writer   writer
     * @return void
     * @author pyf
     * @date 2021/11/3 16:20
     */
    public static void downloadExcel(HttpServletResponse response, String fileName, ExcelWriter writer) {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        // test.xls是彈出下載對話框的文件名,不能為中文,中文請自行編碼
        ServletOutputStream out = null;
        try {
            // 設置請求頭屬性
           // response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), StandardCharsets.ISO_8859_1));
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), StandardCharsets.UTF_8));
            out = response.getOutputStream();
            // 寫出到文件
            writer.flush(out, true);
            // 關閉writer,釋放內存
            writer.close();
            // 此處記得關閉輸出Servlet流
            IoUtil.close(out);
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 自適應寬度(中文支持)
     * @param sheet
     * @param size 因為for循環從0開始,size值為 列數-1
     */
    public static void setSizeColumn(Sheet sheet, int size) {
        for (int columnNum = 0; columnNum <= size; columnNum++) {
            int columnWidth = sheet.getColumnWidth(columnNum) / 256;
            for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row currentRow;
                //當前行未被使用過
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }

                if (currentRow.getCell(columnNum) != null) {
                    Cell 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);
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM