Java解析Excel生成Word POI Spire.Doc
前言
写文档的时候需要将Excel中整理的功能点按一定的格式插入到word文档中。项目的功能点比较多,手动搬运耗时耗力,打算偷个懒,用代码帮一下忙。
逻辑:读取Excel文件进行解析->生成word文档
工具:
1、Apache POI:解析Excel
2、Spire.Doc:生成word
Free Spire.Doc for Java 官网地址:https://www.e-iceblue.cn/Introduce/Spire-Doc-JAVA.html
所需依赖:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>RELEASE</version>
</dependency>
</dependencies>
Demo
Controller:
/**
* 通过excel生成Word
*
* @param multipartFile Excel
* @return
*/
@PostMapping(value = "/excel2word")
@ApiOperation(value = "通过excel生成Word", httpMethod = "POST")
public void excelToWord(MultipartFile multipartFile,HttpServletResponse response) {
service.excelToWord(multipartFile,response);
}
Service:
public void importExcelToWord(MultipartFile multipartFile, HttpServletResponse response) {
try {
Workbook workbook = new HSSFWorkbook(new POIFSFileSystem(multipartFile.getInputStream()));
// 获取第一个张sheet
Sheet sheet = workbook.getSheetAt(0);
//创建Word文档
Document doc = new Document();
//添加一个目录的section 添加分页
Section section = doc.addSection();
Paragraph para = section.addParagraph();
TextRange tr = para.appendText("目 录");
//设置字体大小和颜色
tr.getCharacterFormat().setTextColor(Color.black);
tr.getCharacterFormat().setFontName("宋体");
tr.getCharacterFormat().setFontSize(20);
para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
//设置段后间距
para.getFormat().setAfterSpacing(10);
//添加段落
para = section.addParagraph();
//通过指定最低的Heading级别1和最高的Heading级别3,创建包含Heading 1、2、3,制表符前导符和右对齐页码的默认样式的Word目录。标题级别范围必须介于1到9之间
para.appendTOC(1, 9);
section = doc.addSection();
section.addParagraph();
Paragraph paraTitle3 = section.addParagraph();
paraTitle3.appendText("一级标题");
paraTitle3.applyStyle(BuiltinStyle.Heading_1);
// 遍历Excel行
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
// 从第二行开始
Row row = sheet.getRow(i);
Cell tempTitle = row.getCell(0);
String function = row.getCell(2).getStringCellValue();
String description = row.getCell(3).getStringCellValue();
String type = row.getCell(5).getStringCellValue();
//添加一个段落
para = section.addParagraph();
para.appendText(application);
//应用Heading 2样式到段落
para.applyStyle(BuiltinStyle.Heading_2);
//section.addParagraph();
//添加标题
Paragraph paraTitle4 = section.addParagraph();
paraTitle4.appendText(function);
//应用Heading 3样式到段落
paraTitle4.applyStyle(BuiltinStyle.Heading_3);
//section.addParagraph();
//添加描述
Paragraph paraDesc = section.addParagraph();
paraDesc.appendText(description);
paraDesc.applyStyle(BuiltinStyle.Body_Text);
//section.addParagraph();
//给第一个段落和第二个段落设置水平居中对齐方式
//paraText.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
}
//获取第一个节中的页脚
HeaderFooter footer = doc.getSections().get(0).getHeadersFooters().getFooter();
//添加段落到页脚
Paragraph footerParagraph = footer.addParagraph();
//添加文字、页码域和总页数域到段落
footerParagraph.appendText("第");
footerParagraph.appendField("page number", FieldType.Field_Page);
footerParagraph.appendText("页");
footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
//设置目录页码数字格式为罗马数字
doc.getSections().get(0).getPageSetup().setPageNumberStyle(PageNumberStyle.Roman_Lower);
//设置内容页码数字格式为阿拉伯数字
doc.getSections().get(1).getPageSetup().setPageNumberStyle(PageNumberStyle.Arabic);
//设置第二节页码从新开始编码,并设置起始页码数字
doc.getSections().get(1).getPageSetup().setRestartPageNumbering(true);
doc.getSections().get(1).getPageSetup().setPageStartingNumber(1);
//更新目录
doc.updateTableOfContents();
//保存到临时固定地址
String path = "D:";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
//生成临时文件保存到本地
String filePath = path + File.separator + UUID.randomUUID();
doc.saveToFile(filePath + ".docx", FileFormat.Docx);
//重新读取文档,进行操作
InputStream is = new FileInputStream(filePath + ".docx");
XWPFDocument document = new XWPFDocument(is);
//以上Spire.Doc 生成的文件会自带警告信息,这里来删除Spire.Doc 的警告
document.removeBodyElement(0);
//输出word内容文件流,提供下载
response.reset();
response.setContentType("application/x-msdownload");
String fileName = "" + application + ".docx";
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
OutputStream servletOS = null;
try {
servletOS = response.getOutputStream();
document.write(ostream);
servletOS.write(ostream.toByteArray());
servletOS.flush();
servletOS.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}