当前位置:网站首页>POI operation word template replaces data and exports word
POI operation word template replaces data and exports word
2022-04-23 14:03:00 【one billion twenty-nine million one hundred and seventy-nine th】
One 、 Preface
poi operation word Template replacement data , It's simple , Not many algorithms are involved . I will provide poi Of jar package . The core idea is to word The part that needs to be replaced is written as a keyword , In operation word When , Replace with the data we filled in according to the keyword .
Two 、poi download
WeChat official account search : The small white XBIT
Reply key :poi, You can download .
3、 ... and 、 Realization
1、 take word The template is placed in a fixed path, such as :D:\poi\inpoi\ Credit reporting ****.docx
2、 Match the data you want to replace with keywords to replace . adopt java Of Map The structure is similar to json Data format , The acquired data put go in . Here we need to pay attention to ,map Of key It must be with word The template of key identical , To replace . Another thing to note is , If the replacement is not successful , Need to put word Of key Rewrite it in your notebook , Copy and paste to word That's all right. .
3、 Core code
(1) Send the data from the front end , Put in map in
Key structures map Perform data replacement , The tool class for a while needs to use map
/*
* Handle the ID card information of the borrower and the guarantor
*/
@RequestMapping("jkr")
@ResponseBody
public JSONObject test(@RequestParam("name") String name,@RequestParam("sex") String sex,@RequestParam("idnum")
String idnum,@RequestParam("add") String add,@RequestParam("tel") String tel,@RequestParam("type") String type,
HttpServletRequest request) {
/*
* The borrower ===1 map1
* Borrower's spouse ===2 map2
* guarantor 1===3 map3
* guarantor 1 spouse ===4 map4
* guarantor 2===5 map5
* guarantor 2 spouse ===6 map6
* guarantor 3===7 map7
* guarantor 3 spouse ===8 map8
*/
if(type.equals(" The borrower ")) {
request.getSession().setAttribute("type1", type);
// newly build map1
Map<String, String> map1=new HashMap<String, String>();
map1.put("name1", name);
map1.put("sex1", sex);
map1.put("idnum1", idnum);
map1.put("add1", add);
map1.put("tel1", tel);
// Put the borrower's information into session in
request.getSession().setAttribute("jkr", map1);
//System.out.println(type+map1);
}
(2) Replace
// File path
String srcPath = "D:\\poi\\inpoi\\ Credit reporting \\****.docx";
// New file path
String destPath = "D:\\poi\\outpoi\\****.doc";
wordUtils word=new wordUtils();
// After finishing word transformation
String status=word.writer(srcPath, destPath, combineResultMap);
wordUtils It's the realization of word Tool class for text substitution
The specific code is as follows
public class wordUtils {
public String allwrite(String inputSrc, String outSrc, Map<String,String> map) {
try {
// Judge whether the file exists
File file = new File(inputSrc);
if(!file.exists()){
return "fail";
}else {
// obtain .docx File extractor
XWPFDocument doc = new XWPFDocument(POIXMLDocument.openPackage(inputSrc));
/**
* Replace the text specified in the paragraph
*/
for(XWPFParagraph p : doc.getParagraphs()){
List<XWPFRun> runs = p.getRuns();
if(runs != null){
for(XWPFRun r : runs){
// Text to replace
String text = r.getText(0);
// Replace specified text
for(String key : map.keySet()){
if(text != null && text.equals(key)){
// Pay attention when replacing ,setText There are two parameters
// The first is the replacement text , The second is where to start the replacement
//0 Yes, replace all , If not set, the default is from the original text
// Append at the end
r.setText(map.get(key),0);
}
}
}
}
}
for(XWPFTable tab : doc.getTables()){
for(XWPFTableRow row : tab.getRows()){
for(XWPFTableCell cell : row.getTableCells()){
// Be careful ,getParagraphs It must not be missed
// Because there may be multiple words that need to be replaced in a table
// Without this step, the text cannot be replaced
for(XWPFParagraph p : cell.getParagraphs()){
for(XWPFRun r : p.getRuns()){
String text = r.getText(0);
for(String key : map.keySet()){
if(text.equals(key)){
r.setText(map.get(text),0);
}
}
}
}
}
}
}
doc.write(new FileOutputStream(outSrc));
return "succ";
}
} catch (IOException e) {
e.printStackTrace();
return "succ";
}
}
/*
* Handle word Paragraph inside
*/
public String wzwrite(String inputSrc, String outSrc, Map<String,String> map) {
try {
// Judge whether the file exists
File file = new File(inputSrc);
if(!file.exists()){
return "fail";
}else {
// obtain .docx File extractor
XWPFDocument doc = new XWPFDocument(POIXMLDocument.openPackage(inputSrc));
/**
* Replace the text specified in the paragraph
*/
for(XWPFParagraph p : doc.getParagraphs()){
List<XWPFRun> runs = p.getRuns();
if(runs != null){
for(XWPFRun r : runs){
// Text to replace
String text = r.getText(0);
// Replace specified text
for(String key : map.keySet()){
if(text != null && text.equals(key)){
// Pay attention when replacing ,setText There are two parameters
// The first is the replacement text , The second is where to start the replacement
//0 Yes, replace all , If not set, the default is from the original text
// Append at the end
r.setText(map.get(key),0);
}
}
}
}
}
doc.write(new FileOutputStream(outSrc));
return "succ";
}
} catch (IOException e) {
e.printStackTrace();
return "succ";
}
}
/*
* Handle word The table inside
*/
public static String writer(String inputSrc, String outSrc, Map<String,String> map) {
try {
// Judge whether the file exists
File file = new File(inputSrc);
if(!file.exists()){
return "fail";
}else {
// obtain .docx File extractor
XWPFDocument doc = new XWPFDocument(POIXMLDocument.openPackage(inputSrc));
System.out.println(" type :"+doc.getClass().getName().toString());
/**
*
Get all paragraphs :List<XWPFParagraph> paragraphs = word.getParagraphs();
Get all... In a paragraph Runs:List<XWPFRun> xwpfRuns = xwpfParagraph.getRuns();
Get one Runs One of them Run:XWPFRun run = xwpfRuns.get(index);
doc.getTables() Get all the tables
tab.getRows() Get all rows in a table
row.getTableCells() Get all the columns in a row
cell.getParagraphs() Get the content in a box
*/
for(XWPFTable tab : doc.getTables()){
for(XWPFTableRow row : tab.getRows()){
for(XWPFTableCell cell : row.getTableCells()){
// Be careful ,getParagraphs It must not be missed
// Because there may be multiple words that need to be replaced in a table
// Without this step, the text cannot be replaced
for(XWPFParagraph p : cell.getParagraphs()){
for(XWPFRun r : p.getRuns()){
String text = r.getText(0);
for(String key : map.keySet()){
if(text.equals(key)){
r.setText(map.get(text),0);
}
}
}
}
}
}
}
doc.write(new FileOutputStream(outSrc));
return "succ";
}
} catch (IOException e) {
e.printStackTrace();
return "succ";
}
}
}
Due to work involved , Inconvenient to word Give me your template , This is the way to realize the answer .
The effect can be seen in the official account.
Print word You can read this article :https://zhuanlan.zhihu.com/p/165458446
版权声明
本文为[one billion twenty-nine million one hundred and seventy-nine th]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231401298335.html
边栏推荐
- The latest development of fed digital currency
- Function executes only the once function for the first time
- Android: answers to the recruitment and interview of intermediate Android Development Agency in early 2019 (medium)
- 基于ibeacons签到系统
- 蓝绿发布、滚动发布、灰度发布,有什么区别?
- freeCodeCamp----arithmetic_ Arranger exercise
- BUG_me
- Basic knowledge learning record
- Prediction of tomorrow's trading limit of Low Frequency Quantization
- 读了一篇博客,重新理解闭包整理一下
猜你喜欢
freeCodeCamp----arithmetic_ Arranger exercise
smart-doc + torna生成接口文档
Prediction of tomorrow's trading limit of Low Frequency Quantization
As a junior college student, I studied hard in closed doors for 56 days, won Ali offer with tears, five rounds of interviews and six hours of soul torture
Ptorch classical convolutional neural network lenet
Interesting talk about network protocol
记录一个奇怪的bug:缓存组件跳转之后出现组件复制
Port occupied 1
linux安装mysql后修改密码
try --finally
随机推荐
趣谈网络协议
How does redis solve the problems of cache avalanche, cache breakdown and cache penetration
visio安装报错 1:1935 2:{XXXXXXXX...
基于CM管理的CDH集群集成Phoenix
烟雾传感器(mq-2)使用详细教程(基于树莓派3b+实现)
Special test 05 · double integral [Li Yanfang's whole class]
mysql新表,自增id长达20位,原因竟是......
mysql通过binlog文件恢复数据
AtCoder Beginner Contest 248C Dice Sum (生成函数)
redis如何解决缓存雪崩、缓存击穿和缓存穿透问题
json反序列化匿名数组/对象
33 million IOPs, 39 microsecond delay, carbon footprint certification, who is serious?
Intégration de Clusters CDH Phoenix basée sur la gestion cm
STM32 learning record 0007 - new project (based on register version)
Atcoder beginer contest 248c dice sum (generating function)
PySide2
理解虚基类、虚函数与纯虚函数的概念(转)
Haruki Murakami -- Excerpt from "what do I talk about when I talk about running"
分库分表 & ShardingSphere
Node接入支付宝开放平台的沙箱实现支付功能