JAVA导出Word文档工具EasyWord

发布于:2023-04-27 ⋅ 阅读:(623) ⋅ 点赞:(0)

介绍

  • 基于Apache poi封装,在上层做了模型转换的封装,让使用者更加简单方便

  • 只支持docx的导出,不支持doc

    下面废话少说 让我们以最快的方式学会用java导出word文档

组件依赖

依赖 版本 备注
lombok 1.18.10
poi 5.1.0
poi-ooxml 5.1.0
poi-scratchpad 5.1.0

使用教程

1.引入依赖

<dependency>
    <groupId>com.sushengren</groupId>
    <artifactId>easyword</artifactId>
    <version>1.1.3</version>
</dependency>

2.制作word模板

在这里插入图片描述

3.编写测试类

@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DemoData {

    @WordProperty("标题")
    private String title;

    @WordProperty("生成时间")
    private String generationTime;

    @WordProperty("学生数")
    private Integer numberOfStudents;

    @WordProperty("监考老师数")
    private Integer numberOfInvigilators;

    @WordProperty("评卷老师数")
    private Integer numberOfTeachers;

    @WordProperty("年度")
    private String year;

    @WordProperty("学期")
    private String semester;

    @WordProperty("考试时间")
    private String examinationTime;

    @WordProperty("科目")
    private String subject;

    @WordProperty(value = "Logo", converter = PictureConverter.class)
    private InputStream logo;

    @WordProperty("班级列表")
    private List<ClassInfo> classList;

    @Getter
    @Setter
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ClassInfo {

        @WordProperty("班级")
        private String className;

        @WordProperty("人数")
        private Integer numberOfPeople;

        @WordProperty("平均分")
        private Double theAverageScore;

        @WordProperty("年级")
        private String grade;

        @WordProperty("排名")
        private Integer ranking;

        @WordProperty("班主任")
        private String classTeacher;

        @WordProperty("学生列表")
        private List<StudentInfo> studentList;

    }

    @Getter
    @Setter
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class StudentInfo {

        @WordProperty("姓名")
        private String name;

        @WordProperty("学号")
        private String studentID;

        @WordProperty("总分")
        private Double totalScore;

        @WordProperty("平均分")
        private Double theAverageScore;

        @WordProperty("排名")
        private Integer ranking;

        @WordProperty("年级排名")
        private Integer gradeRanking;

        @WordProperty("备注")
        private String remark;

    }

}

public static void main(String[] args) throws IOException {
        List<StudentInfo> studentList = new ArrayList<>();
        studentList.add(new StudentInfo("小明", "No00001", 280.0, 93.3, 1, 1, ""));
        studentList.add(new StudentInfo("小红", "No00002", 260.0, 86.6, 2, 2, ""));
        studentList.add(new StudentInfo("小花", "No00003", 270.0, 90.0, 3, 120, ""));
        studentList.add(new StudentInfo("小莉", "No00004", 250.0, 83.3, 4, 210, ""));
        studentList.add(new StudentInfo("托尼", "No00005", 241.0, 80.3, 5, 600, ""));

        List<ClassInfo> classList = new ArrayList<>();
        classList.add(new ClassInfo("一年级一班", 50, 270.5, "一年级", 1, "温娟", studentList));
        classList.add(new ClassInfo("一年级二班", 60, 260.5, "一年级", 2, "张三", studentList));
        classList.add(new ClassInfo("一年级三班", 35, 280.5, "一年级", 3, "李四", studentList));
        classList.add(new ClassInfo("一年级四班", 56, 290.5, "一年级", 4, "王五", studentList));

        DemoData data = DemoData.builder()
                .title("2022年度期末考试成绩报告")
                .generationTime("2022-01-01")
                .numberOfStudents(1510)
                .numberOfInvigilators(157)
                .numberOfTeachers(157)
                .year("二零二二")
                .semester("第二学期")
                .examinationTime("2022-10-01 至 2022-10-02")
                .subject("语文、数学、英语")
                .classList(classList)
                .logo(new FileInputStream("C:\\Users\\mangfu\\Pictures\\logo.png"))
                .build();

        File file = new File("C:\\Users\\mangfu\\Desktop\\期末成绩报告模板.docx");
        FileOutputStream out = new FileOutputStream("C:\\Users\\mangfu\\Desktop\\期末成绩报告模板-1.docx");
        EasyWord.of(file).doWrite(data).toOutputStream(out);
    }

4.模板输出word文件

在这里插入图片描述

接口方式

  /**
     * 导出word文件
     */
    @ApiOperation("学习成绩报表")
    @GetMapping("/download")
    public void download(HttpServletResponse response, String param1, String param2) throws IOException {

        if(Strings.isNullOrEmpty(param1) || Strings.isNullOrEmpty(param2)){
            return;
        }

        try {
        	//设置浏览器导出excl格式文件
        	//response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.sheet");
            //设置浏览器导出word格式文件
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            //设置字符集
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码  注意这里Chrome仍然会乱码
            String fileName = URLEncoder.encode(tableName, "UTF-8").replaceAll("\\+", "%20");
            //设置导出excl文件格式
            //response.setHeader("Content-Disposition", "attachment;utf-8;filename=" + fileName + ".xlsx");
            //设置导出word文件格式
            response.setHeader("Content-Disposition", "attachment;utf-8;filename=" + fileName + ".docx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

            //todo获取表信息
			
            //todo获取表字段信息

            TableInfo data = TableInfo.builder()
                      .title("2022年度期末考试成绩报告")
                .generationTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date()))
                .numberOfStudents(1510)
                .numberOfInvigilators(157)
                .numberOfTeachers(157)
                .year("二零二二")
                .semester("第二学期")
                .examinationTime("2022-10-01 至 2022-10-02")
                .subject("语文、数学、英语")
                .classList(classList)
                .logo(new FileInputStream("C:\\Users\\mangfu\\Pictures\\logo.png"))
                .build();

			//获取resources下目中录模板文件
            //File file = new ClassPathResource("xxx/xxx.docx").getFile();
            //以流的形式 获取resources下目中录模板文件
            InputStream file = new ClassPathResource("xxx/xxx.docx").getInputStream();
            EasyWord.of(file).doWrite(data).toOutputStream(response.getOutputStream());

        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

总结

java导出word文档 的使用方式还有很多 以最简单的方式学习 希望能够帮助到各位!

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到