EasyPOI导出Word简单版

在实际开发中,我们可能会遇到用word导出表格数据的场景。

1. 设置模板

简单的参数我们用{{param}}在模板里设置,然后在代码里填充。如下图:
在这里插入图片描述
如果要批量导出数据,我们可以先设置表头,然后通过代码导出数据。如下图:
在这里插入图片描述

2. 编写代码

2.1 添加依赖

        <!-- Excel = EasyPoi -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.0.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-lang3</artifactId>
                    <groupId>org.apache.commons</groupId>
                </exclusion>
            </exclusions>
        </dependency>

2.2 编写实体类

package com.mayi1203.myproject.entity;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

/**
 * 学生类
 * @author mayi1203
 * @date 2020年5月8日
 */
@Data
public class Student implements Serializable {
    private static final long serialVersionUID = 2131321500629905052L;
    
    @Excel(name = "学生姓名")
    private String studentName;

    @Excel(name = "学生年龄")
    private Integer age;
    
    @Excel(name = "学生生日", importFormat = "yyyy/MM/dd", exportFormat = "yyyy/MM/dd")
    private Date birthday;
    
    @Excel(name = "语文成绩")
    private BigDecimal chineseScore;
    
    @Excel(name = "数学成绩")
    private BigDecimal mathScore;
    
}

2.3 编写controller层

package com.mayi1203.myproject.controller;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mayi1203.myproject.entity.Student;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.params.ExcelListEntity;
import cn.afterturn.easypoi.word.parse.excel.ExcelEntityParse;

@RestController
@RequestMapping(value = "/v1/test")
public class TestController {
	private static final String TEMPLATE_FILE_NAME = "word/template.docx";
	
	@GetMapping("exportWord")
	public void exportWord(HttpServletResponse response) throws Exception {
		// 填充参数
		Map<String, Object> map = new HashMap<>(9);
		map.put("0", "one");
		map.put("1", "two");
		map.put("2", "three");
		map.put("3", "four");
		map.put("4", "five");
		map.put("5", "six");
		
		XWPFDocument document = WordExportUtil.exportWord07(TEMPLATE_FILE_NAME, map);
		List<Student> list = new ArrayList<>(2);
		this.addStudents(list);
		// 导出批量数据
		new ExcelEntityParse().parseNextRowAndAddRow(document.getTableArray(1), 1, new ExcelListEntity(list, Student.class, 1));
		
        String fileName = System.currentTimeMillis() + ".docx";
        response.reset();
        response.setContentType("application/msword");
        String dispositionValue = "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", dispositionValue);
        response.setCharacterEncoding("UTF-8");
        OutputStream output = response.getOutputStream();
        document.write(output);
        document.close();
        output.close();
	}
	
	private void addStudents(List<Student> list) {
		Student stu = new Student();
		stu.setStudentName("wuyuan");
		stu.setAge(11);
		stu.setBirthday(new Date());
		stu.setChineseScore(new BigDecimal("88"));
		stu.setMathScore(new BigDecimal("85.5"));
		list.add(stu);
		stu = new Student();
		stu.setStudentName("lisi");
		stu.setAge(12);
		stu.setBirthday(new Date());
		stu.setChineseScore(new BigDecimal("87"));
		stu.setMathScore(new BigDecimal("89"));
		list.add(stu);
	}
}

2.4 调用接口,效果如下图:
在这里插入图片描述
由于笔者水平有限,本博客难免有不足,恳请各位大佬不吝赐教!

使用 EasyPoi 导出 Word 文档需要进行以下步骤: 1. 引入 EasyPoi 依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>5.2.0</version> </dependency> ``` 2. 创建模板 在 Word 文档中创建一个需要填充数据的模板,可以使用 Word 编辑器创建一个包含标签的文档。标签可以在文档中使用 ${} 表示。 例如,创建一个包含用户信息的模板,可以在 Word 文档中添加以下内容: ``` 姓名:${name} 年龄:${age} ``` 3. 创建数据源 创建一个 Java 类,包含需要导出的数据,例如: ```java public class User { private String name; private int age; // 省略 getter 和 setter 方法 } ``` 4. 使用 EasyPoi 导出 Word 文档 在 Java 代码中使用 EasyPoi 提供的 API 将数据填充到模板中,并将生成的 Word 文档保存到本地磁盘。例如: ```java // 创建模板对象 XWPFTemplate template = XWPFTemplate.compile("template.docx").render(data); // 将数据填充到模板中 Map<String, Object> data = new HashMap<>(); data.put("name", "张三"); data.put("age", 18); // 导出 Word 文档 try (FileOutputStream out = new FileOutputStream("output.docx")) { template.write(out); } template.close(); ``` 上述代码中,XWPFTemplate.compile("template.docx") 表示创建一个模板对象,template.render(data) 表示将数据填充到模板中,FileOutputStream("output.docx") 表示将生成的 Word 文档保存到本地磁盘。 以上就是使用 EasyPoi 导出 Word 文档的步骤。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值