资讯 小学 初中 高中 语言 会计职称 学历提升 法考 计算机考试 医护考试 建工考试 教育百科
栏目分类:
子分类:
返回
空麓网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
空麓网 > 计算机考试 > 软件开发 > 后端开发 > Java

SpringBoot使用Apache POI导出Word

Java 更新时间: 发布时间: 计算机考试归档 最新发布

SpringBoot使用Apache POI导出Word

最近有一个业务是根据用户的输入动态生成word,其中包括动态表格,以下是博主的实现方式

1、引入pom依赖

      org.apache.poi      poi      4.1.2              org.apache.poi      poi-ooxml      4.1.2    

这里博主用的是4.1.2版本,之前用的5.x版本总是报InvalidFormatException异常,至今没找到原因,有知道的小伙伴也可以在评论区给出解决办法

2、创建传输对象PersonDto

import lombok.Data;import java.util.List;@Datapublic class PersonDto {    private String name;//姓名    private Integer age;//年龄    private String practiceDuration;//练习时长    private List interest;//兴趣爱好}

3、控制层代码

@RestController@RequestMapping("/test")public class TestController {	@Autowired    private TestService testService;	@GetMapping("/export")    public void renewalExport(PersonDto dto, HttpServletResponse response){        testService.export(dto,response);    }}

ps:传输数据多的话可以使用post请求,使用@RequestBody 注解

4、业务层代码

@Service@Slf4jpublic class TestService {	public void export(PersonDto dto,HttpServletResponse response) {        InputStream in = null;        XWPFDocument doc = null;        try {            // 1. 创建 Word 文档对象            ClassPathResource resource = new ClassPathResource("模板.docx");//如果是doc格式的话下面创建的对象是new HSSFWorkbook()            in = resource.getInputStream();            doc = new XWPFDocument(in);            //创建测试数据            dto.setAge(25);            dto.setName("坤坤");            dto.setPracticeDuration("两年半");            List list = new ArrayList(){{                add("唱");                add("跳");                add("rap");                add("篮球");            }};            dto.setInterest(list);            // 2. 填充文本内容            Map textMap = new HashMap<>();            textMap.put("name", dto.getName());            textMap.put("age", String.valueOf(dto.getAge()));            textMap.put("practiceDuration", dto.getPracticeDuration());            for (XWPFParagraph p : doc.getParagraphs()) {                List runs = p.getRuns();                if (runs != null) {                    for (XWPFRun run : runs) {                        String text = run.getText(0);                        if (text != null) {                            for (Map.Entry entry : textMap.entrySet()) {                                if (text.contains(entry.getKey())) {                                    text = text.replace(entry.getKey(), entry.getValue());                                    run.setText(text, 0);                                }                            }                        }                    }                }            }            // 定位到第一个表格并获取其第一行(即标题行)            XWPFTable table = doc.getTables().get(0);            // 获取每列的索引            for (int i = 1; i <= dto.getInterest().size(); i++) {                String data = dto.getInterest().get(i - 1);                XWPFTableRow row = table.createRow();                // 根据列名索引获取单元格(这里以第一列“序号”作为示例)                XWPFTableCell cell1 = row.getCell(0);                if (cell1 == null) {                    cell1 = row.createCell();                }                cell1.setText(String.valueOf(i)); // 序号加1                // 根据列名依次填充单元格的文本内容                XWPFTableCell cell2 = row.getCell(1);                if (cell2 == null) {                    cell2 = row.createCell();                }                cell2.setText(data); // 产品名称            }            // 将文档保存到输出流中并设置响应头            String fileName = "test.docx";            response.setContentType("application/force-download");            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1"));            doc.write(response.getOutputStream());            response.flushBuffer();        } catch (IOException e) {            // 处理异常...            log.error(e.getMessage(),e);        } finally {            try {                in.close();            } catch (Exception e) {            }        }    }}

5、word模板(放在resources目录下)

6、输出word

以上就是实现word导出的全部过程,博主目前还有一个问题没有解决就是动态表格的内容样式不能根据表头的样式来,希望有小伙计解决并指出。

转载请注明:文章转载自 http://www.konglu.com/
本文地址:http://www.konglu.com/it/1096084.html
免责声明:

我们致力于保护作者版权,注重分享,被刊用文章【SpringBoot使用Apache POI导出Word】因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理,本文部分文字与图片资源来自于网络,转载此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请立即通知我们,情况属实,我们会第一时间予以删除,并同时向您表示歉意,谢谢!

我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2023 成都空麓科技有限公司

ICP备案号:蜀ICP备2023000828号-2