当前位置: 首页 > 后端技术 > Java

SpringBoot集成文档-如何使用POI导出Word文档?

时间:2023-04-02 01:59:07 Java

在上一篇文章中,我们介绍了通过ApachePOI导出excel,ApachePOI包含了一个运行OfficeOpenXML(OOXML)标准和微软的OLE2复合文档格式(OLE2)的JavaAPI。所以也可以通过POI导出word。本文主要介绍Word通过SpringBoot集成POI工具的导出功能。@pdaiSpringBoot综合文档-集成POIWord导出知识准备什么是POI实现案例Pom依赖导出Word示例源码参考文档更多内容知识准备需要了解ApachePOI遵循的标准(OfficeOpenXML(OOXML)标准和微软的OLE2CompoundDocumentFormat(OLE2)),会对应API的依赖包。@pdai什么是POIA?ApachePOI是一个用Java编写的免费开源跨平台JavaAPI。ApachePOI为Java程序提供了一个API来读写MicrosoftOffice格式的文件。POI是“PoorObfuscationImplementation”的首字母缩写,意思是“模糊实现的简洁版”。ApachePOI是一个JavaAPI,用于创建和维护符合OfficeOpenXML(OOXML)标准和Microsoft的OLE2复合文档格式(OLE2)的操作。有关详细信息,请参阅官方文档。实现案例这里是一个SpringBoot集成POI导出用户信息的Word例子。pom依赖引入poi的依赖包org.apache.poipoi5.2.2org.apache.poipoi-ooxml5.2.2导出WordUserController中导出的方法packagetech.pdai.springboot.file.word。poi.controller;导入java.io.OutputStream;导入javax.servlet.http.HttpServletResponse;导入io.swagger.annotations.ApiOperation;导入org.apache.poi.xwpf.usermodel.XWPFDocument;导入org.springframework.beans.factory.annotation.Autowired;导入org.springframework.web.bind.annotation.GetMapping;导入org.springframework.web.bind.annotation.RequestMapping;导入org.springframework.web.bind.annotation.RestController;导入tech.pdai.springboot.file.word.poi.service.IUserService;/***@authorpdai*/@RestController@RequestMapping("/user")publicclassUserController{@AutowiredprivateIUserServiceuserService;@ApiOperation("下载Word")@GetMapping("/word/download")publicvoiddownload(HttpServletResponseresponse){try{XWPFDocumentdocument=userService.generateWordXWPFDocument();响应.重置();response.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition","attachment;filename=user_world_"+System.currentTimeMillis()+".docx");OutputStreamos=response.getOutputStream();文档.write(os);操作系统关闭();}catch(Exceptione){e.printStackTrace();}}}UserServiceImple中导出Word方法包tech.pdai.springboot.file.word.poi.service.impl;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;导入java.io.InputStream;导入java.math.BigInteger;导入java.util.ArrayList;导入java.util.List;导入lombok.extern.slf4j.Slf4j;导入org.apache.poi。openxml4j.exceptions.InvalidFormatException;导入org.apache.poi.util.Units;导入org.apache.poi.xwpf.usermodel.BreakType;导入org.apache.poi.xwpf.usermodel.Document;导入org.apache.poi。xwpf.usermodel.ParagraphAlignment;导入org.apache.poi.xwpf.usermodel.XWPFDocument;导入org.apache.poi.xwpf.usermodel.XWPFParagraph;导入org.apache.poi.xwpf.usermodel.XWPFRun;导入org.apache。poi.xwpf.usermodel.XWPFTable;导入org.apache.poi.xwpf.usermodel.XWPFTableCell;导入org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;导入org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;导入org.springframework.core.io.ClassPathResource;导入org.springframework.core.io.Resource;导入org.springframework.stereotype.Service;导入tech.pdai.springboot.file.word.poi.entity.User;importtech.pdai.springboot.file.word.poi.service.IUserService;/***@authorpdai*/@Slf4j@ServicepublicclassUserServiceImplimplementsIUserService{@OverridepublicXWPFDocumentgenerateWordXWPFDocument(){XWPFDocumentdoc=newXWPFDocument();//标题createTitle(doc,"Java全栈知识体系");//Chapter1createChapterH1(doc,"1.知识准备");createChapterH2(doc,"1.1什么是兴趣点");createParagraph(doc,"ApachePOI是一个JavaAPI,它创建和维护符合OfficeOpenXML(OOXML)标准和微软的OLE2复合文档格式(OLE2)的操作,可以使用Java读取。并创建、修改MSExcel此外,您还可以使用Java读取和创建MSWord和MSPowerPoint文件。更多信息请参考[官方文档](https://poi.apache.org/index.html)");createChapterH2(doc,"1.2POI中的基本概念");createParagraph(doc,"Whatisthere生成xls和xlsx的区别?POI封装对应Excel中的对象?");//Chapter2createChapterH1(doc,"2.实现案例");createChapterH2(doc,"2.1用户列表示例");createParagraph(doc,"以导出用户列表为例");//tableListuserList=getUserList();XWPFParagraphparagraph=doc.createParagraph();XWPFTabletable=paragraph.getDocument().createTable(userList.size(),5);table.setWidth(500);table.setCellMargins(20,20,20,20);//表格属性CTTblPrtablePr=table.getCTTbl().addNewTblPr();//表格宽度CTTblWidthwidth=tablePr.addNewTblW();width.setW(BigInteger.valueOf(8000));for(inti=0;itableCells=table.getRow(i).getTableCells();tableCells.get(0).setText(userList.get(i).getId()+"");tableCells.get(1).setText(userList.get(i).getUserName());tableCells.get(2).setText(userList.get(i).getEmail());tableCells.get(3).setText(userList.get(i).getPhoneNumber()+"");tableCells.get(4).setText(userList.get(i).getDescription());}createChapterH2(doc,"2.2图片导入示例");createParagraph(doc,"以导出图片为例子");//图片InputStreamstream=null;尝试{XWPFParagraphparagraph2=doc.createParagraph();Resourceresource=newClassPathResource("pdai-guli.png");stream=newFileInputStream(resource.getFile());XWPFRunrun=paragraph2.createRun();run.addPicture(stream,Document.PICTURE_TYPE_PNG,"生成",Units.toEMU(256),Units.toEMU(256));}赶上(IOException|InvalidFormatExceptione){e.printStackTrace();}返回文档;}privatevoidcreateTitle(XWPFDocumentdoc,Stringcontent){XWPFParagraphtitle=doc.createParagraph();title.setAlignment(ParagraphAlignment.CENTER);XWPFRunr1=title.createRun();r1.setBold(true);r1.setFontFamily("宋体");r1.setText(内容);r1.setFontSize(22);}privatevoidcreateChapterH1(XWPFDocumentdoc,Stringcontent){XWPFParagraphactTheme=doc.createParagraph();actTheme.setAlignment(ParagraphAlignment.LEFT);XWPFRunrunText1=actTheme.createRun();runText1.setBold(true);runText1.setText(内容);runText1.setFontSize(18);}privatevoidcreateChapterH2(XWPFDocumentdoc,Stringcontent){XWPFParagraphactType=doc.createParagraph();XWPFRunrunText2=actType.createRun();runText2.setBold(true);runText2.setText(续耳鼻喉科);runText2.setFontSize(15);}privatevoidcreateParagraph(XWPFDocumentdoc,Stringcontent){XWPFParagraphactType=doc.createParagraph();XWPFRunrunText2=actType.createRun();runText2.setText(内容);runText2.setFontSize(11);}privateListgetUserList(){ListuserList=newArrayList<>();for(inti=0;i<5;i++){userList.add(User.builder().id(Long.parseLong(i+"")).userName("pdai"+i).email("pdai@pdai.tech"+i).phoneNumber(121231231231L).description("helloworld"+i).build());}返回用户列表;}}Export导出word示例源码https://github.com/realpdai/t...参考文档https://poi.apache.org/index...更多内容告别碎片化学习,一站式系统学习,不套路后端开发:Java全栈知识体系(https://pdai.tech)