当前位置:网站首页>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
 Insert picture description here

版权声明
本文为[one billion twenty-nine million one hundred and seventy-nine th]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231401298335.html