POI操作word填充数据
程序员文章站
2022-04-11 18:15:14
...
1、pom引入POI包
<!--poid-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
2、POI的XWPFDocument往word模板中填充数据
package com.sx.local.govern.utils;
import com.sx.common.util.FileUtil;
import com.sx.common.util.SpringContextHolder;
import com.sx.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.core.env.Environment;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @deprecated word工具类
* @author lst
* @since 2020-10-26
*/
@Slf4j
public class WordUtils {
private static Environment environment = SpringContextHolder.getBean(Environment.class);
/**
* 根据指定的参数值、模板,生成 word 文档
* @param param 需要替换的变量
* @param templatePath 模板
*/
public static void generateWord(Map<String, Object> param, String templatePath, HttpServletResponse response) {
CustomXWPFDocument doc = null;
try {
OPCPackage pack = POIXMLDocument.openPackage(templatePath);
doc = new CustomXWPFDocument(pack);
// 处理段落
List<XWPFParagraph> paragraphList = doc.getParagraphs();
processParagraphs(paragraphList, param, doc);
// 处理表格
Iterator<XWPFTable> it = doc.getTablesIterator();
while (it.hasNext()) {
XWPFTable table = it.next();
List<XWPFTableRow> rows = table.getRows();
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
List<XWPFParagraph> paragraphListTable = cell.getParagraphs();
processParagraphs(paragraphListTable, param, doc);
}
}
}
// 输出文件
OutputStream outputStream = response.getOutputStream();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + new String((DateUtil.getDateTime14() + ".docx").getBytes(), "ISO8859-1"));
response.setContentType("application/octet-stream");
doc.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
log.error("错误信息:{}",e.getMessage());
}
}
/**
* word单元格水平垂直居中
* @param cell
* @return
*/
public static XWPFTableCell horizontalVerticalCenter(XWPFTableCell cell) {
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);//垂直居中
CTTc cttc = cell.getCTTc();
CTP ctp = cttc.getPList().get(0);
CTPPr ctppr = ctp.getPPr();
if (ctppr == null) {
ctppr = ctp.addNewPPr();
}
CTJc ctjc = ctppr.getJc();
if (ctjc == null) {
ctjc = ctppr.addNewJc();
}
ctjc.setVal(STJc.CENTER); //水平居中
return cell;
}
/**
* 处理段落
*
* @param paragraphList
* @throws FileNotFoundException
* @throws InvalidFormatException
*/
public static void processParagraphs(List<XWPFParagraph> paragraphList, Map<String, Object> param, XWPFDocument doc)
throws InvalidFormatException, FileNotFoundException {
if (paragraphList != null && paragraphList.size() > 0) {
for (XWPFParagraph paragraph : paragraphList) {
List<XWPFRun> runs = paragraph.getRuns();
String text = "", color = "";
for (XWPFRun run : runs) {
try {
String t = run.getText(0);
if (t != null) {
color = run.getColor();
text += t;
}
} catch (Exception e) {
log.info(e.toString());
}
}
if (StringUtil.isNotEmpty(text)) {
boolean isSetText = false;
Boolean flag = true;
for (Map.Entry<String, Object> entry : param.entrySet()) {
String key = entry.getKey();
key = "$" + key ;
if (text.indexOf(key) != -1) {
isSetText = true;
flag = false;
Object value = entry.getValue();
//text = text.replace(key, value.toString());
if (StringUtil.isNotEmpty(value)) {
//替换
if (value instanceof String && (!(value.toString().indexOf("http://") > -1) || !(value.toString().substring(value.toString().lastIndexOf(".")).indexOf(".") > -1))) {
text = text.replace(key, value.toString());
} else {
if (text.indexOf(key) != -1) {
String imgurl = value.toString();
//String type = value.toString().substring(value.toString().length()-3);
String type = value.toString().substring(value.toString().lastIndexOf(".")).replace(".", "");
log.info("文件类型:{}" , type);
if (getPictureType(type) != 4) {
//特殊处理图片
int length = paragraph.getRuns().size();
//将原有的Run去掉
if (length > 0) {
for (int i = (length - 1); i >= 0; i--) {
paragraph.removeRun(i);
}
}
log.info("key:{}" , key);
log.info("imgurl:{}" , imgurl);
String fileNamePath = environment.getProperty("file.uploadPath");
log.info("文件路径:{}" , fileNamePath);
//File file = new File("D://" + imgurl.substring(imgurl.lastIndexOf("/")));
File file = new File(fileNamePath);
String fileStrPath = fileNamePath.substring(0, fileNamePath.lastIndexOf("/") + 1);
log.info("文件夹路径1:{}" ,fileStrPath);
File fileDir = new File(fileStrPath);
if (!fileDir.exists()) {
log.info("创建文件夹");
fileDir.mkdirs();
}
if (!file.exists()) {
log.info("文件不存在,正在完成下载。。。");
//FileUtils.downloadFromNet(imgurl,"D://" + imgurl.substring(imgurl.lastIndexOf("/")));
FileUtil.downloadFromNetByCode(imgurl, fileNamePath);
}
int width = 280;//默认
int height = 200;//默认
CustomXWPFDocument cusDoc = (CustomXWPFDocument) doc;
//String blipId = cusDoc.addPictureData(new FileInputStream(new File("D://" + imgurl.substring(imgurl.lastIndexOf("/")))), getPictureType(type));
String blipId = cusDoc.addPictureData(new FileInputStream(new File(fileNamePath)), getPictureType(type));
cusDoc.createPicture(blipId, doc.getNextPicNameNumber(getPictureType(type)), width, height, paragraph);
}
}
}
} else {
//若value为空,组装""
text = text.replace(key, "");
}
}
}
//说明map中没有模板的key 默认为空
if(flag && text.startsWith("$")){
isSetText = true;
//若value为空,组装""
text = text.replace(text, "");
}
if (isSetText) {
runs.get(0).setText(text, 0);
if (StringUtil.isNotEmpty(color)) {
runs.get(0).setColor(color);
}
for (int i = 1; i < runs.size(); i++) {
runs.get(i).setText("", 0);
}
}
}
}
}
}
/**
* 根据图片类型,取得对应的图片类型代码
*
* @param picType
* @return int
*/
private static int getPictureType(String picType) {
int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
if (picType != null) {
if (picType.equalsIgnoreCase("png")) {
res = CustomXWPFDocument.PICTURE_TYPE_PNG;
} else if (picType.equalsIgnoreCase("dib")) {
res = CustomXWPFDocument.PICTURE_TYPE_DIB;
} else if (picType.equalsIgnoreCase("emf")) {
res = CustomXWPFDocument.PICTURE_TYPE_EMF;
} else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
} else if (picType.equalsIgnoreCase("wmf")) {
res = CustomXWPFDocument.PICTURE_TYPE_WMF;
}
}
return res;
}
public static void main(String[] args) throws Exception {
//调用
Map<String,Object> mapRtn = new HashMap();
mapRtn.put("name","张三");
String temPath = "F:\file\fileUpload\\enclosureOne.docx";
generateWord(mapRtn,temPath,response);
}
/**
* word 转pdf
* @param docxFilePath
* @param pdfFilePath
* @return
*/
public static String convertPdf(String docxFilePath, String pdfFilePath) {
try {
File docxFile = new File(docxFilePath);
//File pdfFile = new File(pdfFilePath);
// 转换pdf文件
if (docxFile.exists()) {
InputStream inStream = new FileInputStream(docxFilePath);
XWPFDocument document = new XWPFDocument(inStream);
// HWPFDocument document = new HWPFDocument(inStream);
OutputStream out = new FileOutputStream(pdfFilePath);
PdfOptions options = PdfOptions.create();
// ExtITextFontRegistry fontProvider=ExtITextFontRegistry.getRegistry();
// options.fontProvider(fontProvider);
PdfConverter.getInstance().convert(document, out, options);
out.close();
inStream.close();
} else {
return "";
}
} catch (Exception e) {
e.printStackTrace();
}
return pdfFilePath;
}
}
3、模板
4、测试
上一篇: java 常见面试题
下一篇: java 常见面试题
推荐阅读
-
PoiDemo【Android将表单数据生成Word文档的方案之二(基于Poi4.0.0)】
-
excel根据rgb自动填充颜色_根据EXCEL数据自动生成WORD文档
-
POI对Word docx文件进行替换数据后字体样式改变问题记录
-
Java向word文档中填充数据
-
Java向word文档中填充数据
-
PoiDemo【Android将表单数据生成Word文档的方案之二(基于Poi4.0.0)】
-
java向word模板中填充数据(总结)
-
Java 将xml模板动态填充数据转换为word文档
-
php操作mysql--连接数据库创建表填充表_MySQL
-
大批量操作数据库表数据技巧 数据数据库word批量