jxls模板快速导出excel

jxls介绍笔者就不多介绍了,大家可以参考jxls官网进行深入学习。

在做java项目时,经常有导出excel的需求,以下是使用jxls快速导出excel的示例,仅供参考。

项目结构如下:


1.引入相关依赖

<dependency>
    <groupId>org.jxls</groupId>
    <artifactId>jxls</artifactId>
    <version>2.4.5</version>
</dependency>
<dependency>
    <groupId>org.jxls</groupId>
    <artifactId>jxls-poi</artifactId>
    <version>1.0.15</version>
</dependency>
<dependency>
    <groupId>org.jxls</groupId>
    <artifactId>jxls-jexcel</artifactId>
    <version>1.0.7</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-jexl</artifactId>
    <version>2.1.1</version>
</dependency>

2.创建pojo

package com.lojzes.model;

/**
 * 备注:
 */
public class Student {

    private int id;

    private String name;

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3.创建jxls模板


4.按照模板生成数据

package com.lojzes;

import com.lojzes.model.Student;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 */
public class App 
{
    public static void main( String[] args )
    {
        List<Student> students = new ArrayList<>();
        students.add(new Student(10,"测试1"));
        students.add(new Student(11,"测试2"));
        String filep = "/student-tpl.xlsx";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(new Date());
        try(InputStream is = App.class.getResourceAsStream(filep)) {
            try (OutputStream os = new FileOutputStream("d:/test_output.xlsx")) {
                Context context = new Context();
                context.putVar("exportDate", format);
                context.putVar("exportTotal", 2);
                context.putVar("exportUser", "测试员");
                context.putVar("students", students);
                JxlsHelper.getInstance().processTemplate(is, os, context);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5.效果预览


猜你喜欢

转载自blog.csdn.net/lyitit/article/details/80800567