0%

javaWord

使用poi操作word

  1. maven依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <!-- word, ppt, excel 文件的读取 -->
    <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.0.0</version>
    </dependency>
    <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>5.0.0</version>
    </dependency>
  2. 代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    import com.fasterxml.jackson.databind.ObjectMapper;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.poi.xwpf.usermodel.*;
    import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;

    import java.io.*;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    /**
    * 相关服务接口
    *

    */
    @Slf4j
    public class WordGenerator {

    /**
    * 修改word到指定的目录
    * @param filename 源文件
    * @param data 模板数据
    * @param dest 目标目录
    * @throws IOException
    */
    public static void modifyWordToDest(File filename, Map<String, Object> data, String dest) throws IOException {
    FileInputStream is = new FileInputStream(filename.getAbsoluteFile());
    modifyWordToDest(is, filename.getName(), data, dest);
    }

    /**
    * 修改word到指定的目录
    * @param is 文件输入流
    * @param fileName 生成文件名
    * @param data 模板数据
    * @param dest 目标目录
    * @throws IOException
    */
    public static void modifyWordToDest(InputStream is, String fileName, Map<String, Object> data, String dest) throws IOException {
    String tmpFilePath = dest + File.separator + fileName;
    File dir = new File(dest);
    if (!dir.exists()) {
    dir.mkdirs();
    }
    FileOutputStream os = new FileOutputStream(tmpFilePath, false);
    try {
    XWPFDocument document = new XWPFDocument(is);

    // 替换段落里面的占位符
    replaceInPara(document, data);

    // 替换表格里的占位符
    tableSearchAndReplace(document, data);

    // 输出
    document.write(os);
    } catch (Exception e) {
    log.error("WordGenerator modifyWordToDest error, fileName:{}",fileName,e);
    } finally {
    close(is);
    close(os);
    }
    }

    /**
    * poi 查找word表格中占位符并替换
    * 表格占位符格式:${name}
    * @param document
    * @param data
    */
    public static final void tableSearchAndReplace(XWPFDocument document, Map<String, Object> data) {
    // 替换表格中的指定文字
    Iterator<XWPFTable> itTable = document.getTablesIterator();

    while (itTable.hasNext()) {
    XWPFTable table = (XWPFTable) itTable.next();

    // 动态处理表格中的list,动态新增行
    Iterator<Map.Entry<String, Object>> dataIterator = data.entrySet().iterator();
    while (dataIterator.hasNext()) {
    Map.Entry<String, Object> entry = dataIterator.next();
    if (entry.getValue() instanceof List) {
    int rcount = table.getNumberOfRows();
    for (int i = rcount - 1; i >= 0; i--) {
    XWPFTableRow row = table.getRow(i);
    boolean findListPara = false;
    List<XWPFTableCell> cells = row.getTableCells();
    for (XWPFTableCell cell : cells) {
    //表格中处理段落(回车)
    List<XWPFParagraph> cellParList= cell.getParagraphs();
    for (XWPFParagraph xwpfParagraph : cellParList) {
    findListPara = findListParaInPara(xwpfParagraph, entry.getKey());
    if (findListPara) {
    break;
    }
    }
    if (findListPara) {
    break;
    }
    }

    /** 处理找到list参数的这行数据 **/
    if (findListPara) {
    // 遍历dataMap,valueList
    List valueList = (List) entry.getValue();
    for (int j = 0; j < valueList.size(); j++) {
    // 设置map值
    ObjectMapper mapObject = new ObjectMapper();
    Map<String, Object> dataMap = mapObject.convertValue(valueList.get(j), Map.class);

    // copy模板行为新增行
    XWPFTableRow sourceRow = new XWPFTableRow((CTRow)table.getRow(i).getCtRow().copy(), table);
    // 新增行替换参数
    replaceInPara(sourceRow, dataMap);
    // 添加到模板行之后
    table.addRow(sourceRow, i + j + 1);

    if (j == valueList.size() - 1) {
    // 最后一次移除模板行
    table.removeRow(i);
    }
    }
    }
    }
    }
    }

    // 处理表格中的替代符
    int rcount = table.getNumberOfRows();
    for (int i = 0; i < rcount; i++) {
    replaceInPara(table.getRow(i), data);
    }
    }
    }

    private static void replaceInPara(XWPFTableRow row, Map<String, Object> data) {
    List<XWPFTableCell> cells = row.getTableCells();
    for (XWPFTableCell cell : cells) {
    //表格中处理段落(回车)
    List<XWPFParagraph> cellParList= cell.getParagraphs();
    for (XWPFParagraph xwpfParagraph : cellParList) {
    replaceInPara(xwpfParagraph, data);
    }
    }
    }

    /**
    * 替换段落里面的变量 段落占位符格式:${name}
    * @param doc
    * @param params
    */
    private static void replaceInPara(XWPFDocument doc, Map<String, Object> params) {
    Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
    XWPFParagraph para;
    while (iterator.hasNext()) {
    para = iterator.next();
    replaceInPara(para, params);
    }
    }

    /**
    * 替换段落里面的变量
    * @param para
    * @param params
    */
    private static void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
    List<XWPFRun> runs;
    Matcher matcher;
    String runText = "";
    int fontSize = 15; // 默认字号
    String fontFamily = "楷体"; // 默认字体
    boolean bold = false; // 默认不加粗

    if (matcher(para.getParagraphText()).find()) {
    runs = para.getRuns();
    if (runs.size() > 0) {
    int j = runs.size();
    for (int i = 0; i < j; i++) {
    XWPFRun run = runs.get(0);
    fontSize = run.getFontSize();
    fontFamily = run.getFontFamily();
    bold = run.isBold();
    String i1 = run.toString();
    runText += i1;
    // 删除
    para.removeRun(0);
    }
    }
    matcher = matcher(runText);

    if (matcher.find()) {
    while ((matcher = matcher(runText)).find()) {
    runText = matcher.replaceFirst(params.get(matcher.group(1)) != null ? String.valueOf(params.get(matcher.group(1))):"");
    }
    // 直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,
    // 所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。
    XWPFRun xwpfRun = para.insertNewRun(0);
    xwpfRun.setBold(bold);
    xwpfRun.setFontSize(fontSize);
    xwpfRun.setFontFamily(fontFamily);
    xwpfRun.setText(runText);
    }
    }
    }
    /**
    * 查询段落里面是list类型的变量
    * @param para
    * @param key
    */
    private static boolean findListParaInPara(XWPFParagraph para, String key) {
    List<XWPFRun> runs;
    String runText = "";
    Matcher matcher;

    if (matcher(para.getParagraphText()).find()) {
    runs = para.getRuns();
    if (runs.size() > 0) {
    int j = runs.size();
    for (int i = 0; i < j; i++) {
    XWPFRun run = runs.get(i);
    runText += run.toString();
    }
    }

    matcher = matcher(runText);

    if (matcher.find()) {
    if (matcher.group(1).equals(key)) {
    return true;
    }
    }
    }
    return false;
    }
    /**
    * 正则匹配字符串
    *
    * @param str
    * @return
    */
    private static Matcher matcher(String str) {
    Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(str);
    return matcher;
    }

    private static void close(InputStream is) {
    if (is != null) {
    try {
    is.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

    private static void close(OutputStream os) {
    if (os != null) {
    try {
    os.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }
    ```
    3. 准备模板文件
    ![docx模板](../image/javaWordTemplate.jpg)

    4. 结果
    ![生成的目录](../image/javaWordFolder.jpg)
    ![目录内容](../image/javaWordResult.jpg)

    ## 遇到的问题及相应的解决方案

    ### jar启动项目遇到的问题
    1. 获取resource目录
    正确方式:

    getClass().getClassLoader().getResourceAsStream(“doc/a.docx”)

    1
    2

    错误方式:

    getClass().getClassLoader().getResource(“doc/a.docx”)

    1
    2
    3
    错误方式在jar包启动的项目中会有问题,具体原因可以网上查下原因,不展开

    2. 获取jar包所在目录路径

    ApplicationHome h = new ApplicationHome(getClass());
    File jarF = h.getSource();
    String sysResPath = jarF.getParentFile().toString();

    [参考](https://blog.csdn.net/liangcha007/article/details/88526181)
  3. getResourceAsStream碰到中文目录
    在本地启动过程时,文件目录采用中文命名(注:不是文件里面的中文内容),例如:new File(“目录/测试.docx”) ,没有任何问题,可以正常读取到。但部署到服务器上通过jar启动,则提示java.io.FileNotFoundException,暂时还未找到解决办法,如果有人了解,可以联系我,一起讨论下。

word中表格动态新增行

可以参考代码