文章目录

  • 一、根据Excel模板导出
  • 1、POI
  • 2、Freemarker
  • 二、EasyExcel
  • 1、导包
  • 2、官网


一、根据Excel模板导出

1、POI

需要poi的包。

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>5.2.5</version>
</dependency>

以下代码可以将以下格式的excel,保留原来的表头:

Java操作Excel大全(持续更新)_List

public static void downLoadTeacherExcel(String outputFilePath, String sourcePath, List<Data> list){
    try (InputStream templateFileInputStream = ExcelUtil.class.getClassLoader().getResourceAsStream("template/"+sourcePath);
         OutputStream outputFileOutputStream = new FileOutputStream(outputFilePath);
         Workbook workbook = new HSSFWorkbook(templateFileInputStream)) {

        Sheet sheet = workbook.getSheetAt(0);

        int rowNumber = 2;
        CellStyle style = workbook.createCellStyle();
        // 设置上边框
        style.setBorderTop(BorderStyle.THIN);
        // 设置下边框
        style.setBorderBottom(BorderStyle.THIN);
        // 设置左边框
        style.setBorderLeft(BorderStyle.THIN);
        // 设置右边框
        style.setBorderRight(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        if(CollectionUtils.isNotEmpty(list)) {
            for (Data data : list) {
                Row row = sheet.createRow(rowNumber++);
                row.setRowStyle(style);
                // 生成每一列excel信息
                row.createCell((short) 0).setCellValue(data.getIdCard()); // 身份证
                // 姓名
                row.createCell((short) 1).setCellValue(data.getName());
                // 性别
                row.createCell((short) 3).setCellValue(data.getSex() == 1 ? "男" : "女");
                // 年龄
                row.createCell((short) 4).setCellValue(data.getAge());
                // 出生日期
                row.createCell((short) 5).setCellValue(data.getBirthday());
                // 民族
                row.createCell((short) 6).setCellValue(data.getNation());
                


            }
        }
        workbook.write(outputFileOutputStream);
        System.out.println("Excel导出成功!");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

2、Freemarker

1、需要的包

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.32</version>
</dependency>

2、准备excel模板:

内容是freemarker的模板格式。

Java操作Excel大全(持续更新)_apache_02

3、另存为xml表格
注意,图片是无法保存的。

4、调整list

Java操作Excel大全(持续更新)_List_03

5、编码

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtil {

    public static void main(String[] args) {
        try {
            // 创建FreeMarker配置,参数是包版本号
//            Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
//            cfg.setClassForTemplateLoading(WordUtil.class, "/"); // 会找到项目路径下
//            cfg.setDefaultEncoding("UTF-8");

            // 加载模板文件 找到resources目录
//            Template template = cfg.getTemplate("template/test.ftl");

            Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
            cfg.setDefaultEncoding("UTF-8");
            cfg.setDirectoryForTemplateLoading(new File("E:\\")); // 指定模板绝对路径
            Template template = cfg.getTemplate("test.xml");


            Map<String, Object> data = new HashMap<>();
            data.put("name", "张三");

            List<Map<String, String>> list = new ArrayList<>();
            Map<String, String> m1 = new HashMap<>();
            m1.put("title", "标题1");
            m1.put("info", "内容1");
            list.add(m1);
            Map<String, String> m2 = new HashMap<>();
            m2.put("title", "标题2");
            m2.put("info", "内容2");
            list.add(m2);
            data.put("maps", list);

            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的文档会因为有无法识别的编码而无法打开
            // utf-8是一定要加的!
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("E:\\output.xlsx"), "utf-8"));
            template.process(data, out);

            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

6、结果

Java操作Excel大全(持续更新)_List_04

二、EasyExcel

1、导包

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.3.4</version>
</dependency>

注意,EasyExcel包含poi相关的包,如果旧的项目用到了,有可能会有兼容问题。

2、官网

https://easyexcel.opensource.alibaba.com/docs/current/