easypoi導出數字類型:easypoi導出word換行

如果遇到poi讀取例如{name}不能識別為一個整體,可以使用word的域操作,如果不太清楚域的使用,可以這麼操作,先在text文檔中寫好,例如{name},然後再整個複製到word中,不要一個一個在word中敲,不然有可能不會被poi識別為一個整體

XWPFDocument對象

POI是apache提供的可以操作word文檔的第三方jar。POI能操作word是使用XWPFDocument對象。

  • XWPFDocument對象可以解析docx文件,在XWPFDocument對象通過輸入流解析docx的時候,會獲取到docx文檔中的各種對象,例如表格,段落,圖片等,通過操作XWPFDocument對象就可以修改模板內容
  • XWPFDocument API結構org.apache.poi.xwpf.usermodel.XWPFDocument
  • XWPFDocument 提供write(OutputStream stream)方法將修改後的對象重新寫入xml並生成新的docx

通過XWPFDocument 可以獲得的docx中的各種對象

POI操作word模板並生成新的word

要具體操作通過XWPFDocument 可以獲得的docx中的各種對象,我們離不開一個對象為XWPFRun對象,API結構
org.apache.poi.xwpf.usermodel.XWPFRun。其描述為:XWPFRun object defines a region of text with a common set of properties。通過描述我們不難理解其作用為設置文本對象的各種屬性。

通過XWPFDocument 獲取對象

//解析docx模板並獲取document對象
XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
//獲取整個文本對象
List<XWPFParagraph> allParagraph = document.getParagraphs();
//獲取整個表格對象
List<XWPFTable> allTable = document.getTables();
//獲取圖片對象
XWPFPictureData pic = document.getPictureDataByID("PICId");

首先建一個很簡單的word模板001.docx,我們通過操作對象獲取word中的文本內容

POI操作word模板並生成新的word

下面demo的輸出可以看出我們操作文本對象,成功獲取了文本內容

@Component("xWPRUNTest")
public class XWPRUNTest {
    //模板文件地址
    private static String inputUrl = "C:\Users\zhihe\Desktop\demo\001.docx";
    public void runTest(){
        
        try {
            //解析docx模板並獲取document對象
            XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
            //獲取整個文本對象
            List<XWPFParagraph> allParagraph = document.getParagraphs();
            
            //獲取XWPFRun對象輸出整個文本內容
            StringBuffer tempText = new StringBuffer();
            for (XWPFParagraph xwpfParagraph : allParagraph) {
                    List<XWPFRun> runList = xwpfParagraph.getRuns();
                    for (XWPFRun xwpfRun : runList) {
                        tempText.append(xwpfRun.toString());
                    }
            }
            System.out.println(tempText.toString());
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

測試

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class runTest {
    
    @Resource
    private XWPRUNTest xWPRUNTest;
    
    @Test
    public void runTest(){
        xWPRUNTest.runTest();
    }

}

控制台輸出結果

POI操作word模板並生成新的word

在這裡發現操作文本對象的時候並沒有獲取到表格文本,所以如果我們需要獲取到表格文本還需要另外的操作

@Component("xWPRUNTableTest")
public class XWPRUNTableTest {
    
    //模板文件地址
    private static String inputUrl = "C:\Users\zhihe\Desktop\demo\001.docx";
    
    public void tableTest(){
        
        try {
            
            StringBuffer tableText = new StringBuffer();
            
            //解析docx模板並獲取document對象
            XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
            //獲取全部表格對象
            List<XWPFTable> allTable = document.getTables();
            
            for (XWPFTable xwpfTable : allTable) {
                //獲取表格行數據
                List<XWPFTableRow> rows = xwpfTable.getRows();
                for (XWPFTableRow xwpfTableRow : rows) {
                    //獲取表格單元格數據
                    List<XWPFTableCell> cells = xwpfTableRow.getTableCells();
                    for (XWPFTableCell xwpfTableCell : cells) {
                        List<XWPFParagraph> paragraphs = xwpfTableCell.getParagraphs();
                        for (XWPFParagraph xwpfParagraph : paragraphs) {
                            List<XWPFRun> runs = xwpfParagraph.getRuns();
                            for(int i = 0; i < runs.size();i++){
                                XWPFRun run = runs.get(i);
                                tableText.append(run.toString());
                            }
                        }
                    }
                }
            }
            
            System.out.println(tableText.toString());
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

測試
成功獲取表格

POI操作word模板並生成新的word

下面我們來對一個wrod進行簡單的修改,首先有個模板word,裡面只有幾個字

POI操作word模板並生成新的word

代碼

public class FirstWordTest {
    
        //模板文件地址
        private static String inputUrl = "C:\Users\zhihe\Desktop\demo\001.docx";
        //新生產的模板文件
        private static String outputUrl = "C:\Users\zhihe\Desktop\demo\test.docx";
        
        /**
         * 
         * @param inputUrl 模板路徑
         * @param outputUrl 模板保存路徑
         */
        public static void changeWord(String inputUrl, String outputUrl ){
            
            try {
                //獲取word文檔解析對象
                XWPFDocument doucument = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
                //獲取段落文本對象
                List<XWPFParagraph> paragraph = doucument.getParagraphs();
                //獲取首行run對象
                XWPFRun run = paragraph.get(0).getRuns().get(0);
                //設置文本內容
                run.setText("修改了的word");
                //生成新的word
                File file = new File(outputUrl);
                
                FileOutputStream stream = new FileOutputStream(file);
                doucument.write(stream);
                stream.close();
                
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public static void main(String[] args) {
            changeWord(inputUrl,outputUrl);
        }
}

測試
運行後生成新的word

POI操作word模板並生成新的word

但是在實際項目中並沒有這麼簡單,模板文檔中可能需要替換文本中的文字,也可能需要替換表格對象中的文字,或者在指定表格中插入數據,下面我們就仿照實際情況來做個簡單的模板。

首先創建一個word的模板

POI操作word模板並生成新的word

工具類

package com.lovo.utils.wordToPdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

/**
 * 通過word模板生成新的word工具類
 * 
 * @author zhiheng
 * 
 */
public class WorderToNewWordUtils {

    /**
     * 根據模板生成新word文檔
     * 判斷表格是需要替換還是需要插入,判斷邏輯有$為替換,表格無$為插入
     * @param inputUrl 模板存放地址
     * @param outPutUrl 新文檔存放地址
     * @param textMap 需要替換的信息集合
     * @param tableList 需要插入的表格信息集合
     * @return 成功返回true,失敗返回false
     */
    public static boolean changWord(String inputUrl, String outputUrl,
            Map<String, String> textMap, List<String[]> tableList) {
        
        //模板轉換默認成功
        boolean changeFlag = true;
        try {
            //獲取docx解析對象
            XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(inputUrl));
            //解析替換文本段落對象
            WorderToNewWordUtils.changeText(document, textMap);
            //解析替換表格對象
            WorderToNewWordUtils.changeTable(document, textMap, tableList);
            
            //生成新的word
            File file = new File(outputUrl);
            FileOutputStream stream = new FileOutputStream(file);
            document.write(stream);
            stream.close();
            
        } catch (IOException e) {
            e.printStackTrace();
            changeFlag = false;
        }
        
        return changeFlag;

    }

    /**
     * 替換段落文本
     * @param document docx解析對象
     * @param textMap 需要替換的信息集合
     */
    public static void changeText(XWPFDocument document, Map<String, String> textMap){
        //獲取段落集合
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        
        for (XWPFParagraph paragraph : paragraphs) {
            //判斷此段落時候需要進行替換
            String text = paragraph.getText();
            if(checkText(text)){
                List<XWPFRun> runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    //替換模板原來位置
                    run.setText(changeValue(run.toString(), textMap),0);
                }
            }
        }
        
    }
    
    /**
     * 替換表格對象方法
     * @param document docx解析對象
     * @param textMap 需要替換的信息集合
     * @param tableList 需要插入的表格信息集合
     */
    public static void changeTable(XWPFDocument document, Map<String, String> textMap,
            List<String[]> tableList){
        //獲取表格對象集合
        List<XWPFTable> tables = document.getTables();
        for (int i = 0; i < tables.size(); i++) {
            //只處理行數大於等於2的表格,且不循環表頭
            XWPFTable table = tables.get(i);
            if(table.getRows().size()>1){
                //判斷表格是需要替換還是需要插入,判斷邏輯有$為替換,表格無$為插入
                if(checkText(table.getText())){
                    List<XWPFTableRow> rows = table.getRows();
                    //遍歷表格,並替換模板
                    eachTable(rows, textMap);
                }else{
//                  System.out.println("插入"+table.getText());
                    insertTable(table, tableList);
                }
            }
        }
    }
    

    
    
    
    /**
     * 遍歷表格
     * @param rows 表格行對象
     * @param textMap 需要替換的信息集合
     */
    public static void eachTable(List<XWPFTableRow> rows ,Map<String, String> textMap){
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                //判斷單元格是否需要替換
                if(checkText(cell.getText())){
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        List<XWPFRun> runs = paragraph.getRuns();
                        for (XWPFRun run : runs) {
                            run.setText(changeValue(run.toString(), textMap),0);
                        }
                    }
                }
            }
        }
    }
    
    /**
     * 為表格插入數據,行數不夠添加新行
     * @param table 需要插入數據的表格
     * @param tableList 插入數據集合
     */
    public static void insertTable(XWPFTable table, List<String[]> tableList){
        //創建行,根據需要插入的數據添加新行,不處理表頭
        for(int i = 1; i < tableList.size(); i++){
            XWPFTableRow row =table.createRow();
        }
        //遍歷表格插入數據
        List<XWPFTableRow> rows = table.getRows();
        for(int i = 1; i < rows.size(); i++){
            XWPFTableRow newRow = table.getRow(i);
            List<XWPFTableCell> cells = newRow.getTableCells();
            for(int j = 0; j < cells.size(); j++){
                XWPFTableCell cell = cells.get(j);
                cell.setText(tableList.get(i-1)[j]);
            }
        }
        
    }
    
    
    
    /**
     * 判斷文本中時候包含$
     * @param text 文本
     * @return 包含返回true,不包含返回false
     */
    public static boolean checkText(String text){
        boolean check  =  false;
        if(text.indexOf("$")!= -1){
            check = true;
        }
        return check;
        
    }
    
    /**
     * 匹配傳入信息集合與模板
     * @param value 模板需要替換的區域
     * @param textMap 傳入信息集合
     * @return 模板需要替換區域信息集合對應值
     */
    public static String changeValue(String value, Map<String, String> textMap){
        Set<Entry<String, String>> textSets = textMap.entrySet();
        for (Entry<String, String> textSet : textSets) {
            //匹配模板與替換值 格式${key}
            String key = "${"+textSet.getKey()+"}";
            if(value.indexOf(key)!= -1){
                value = textSet.getValue();
            }
        }
        //模板未匹配到區域替換為空
        if(checkText(value)){
            value = "";
        }
        return value;
    }
    
    
    
    
    public static void main(String[] args) {
        //模板文件地址
        String inputUrl = "C:\Users\zhihe\Desktop\demo\001.docx";
        //新生產的模板文件
        String outputUrl = "C:\Users\zhihe\Desktop\demo\test.docx";
        
        Map<String, String> testMap = new HashMap<String, String>();
        testMap.put("name", "小明");
        testMap.put("sex", "男");
        testMap.put("address", "軟件園");
        testMap.put("phone", "88888888");
        
        List<String[]> testList = new ArrayList<String[]>();
        testList.add(new String[]{"1","1AA","1BB","1CC"});
        testList.add(new String[]{"2","2AA","2BB","2CC"});
        testList.add(new String[]{"3","3AA","3BB","3CC"});
        testList.add(new String[]{"4","4AA","4BB","4CC"});
        
        WorderToNewWordUtils.changWord(inputUrl, outputUrl, testMap, testList);
    }
}

測試

POI操作word模板並生成新的word

這麼我們就實現了個簡單的POI操作模板完成替換和插入的功能,本來還準備實現固定位置插入圖片的功能,不過發現這是個巨坑,暫時未實現其功能,等以後有空再進行完善,此代碼以docx格式進行演示操作

如果遇到poi讀取例如{name}不能識別為一個整體,可以使用word的域操作,如果不太清楚域的使用,可以這麼操作,先在text文檔中寫好,例如{name},然後再整個複製到word中,不要一個一個在word中敲,不然有可能不會被poi識別為一個整體

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/225870.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-09 14:46
下一篇 2024-12-09 14:47

相關推薦

發表回復

登錄後才能評論