服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|

服务器之家 - 编程语言 - JAVA教程 - springMVC导出word模板的方法

springMVC导出word模板的方法

2020-11-27 11:04初见321 JAVA教程

这篇文章主要为大家详细介绍了springMVC导出word模板的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了springMVC导出word模板的具体代码,供大家参考,具体内容如下

controller 调用

?
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
@RequestMapping(value = "/exportWord")
public void exportWord(HttpServletResponse response, HttpServletRequest request) throws IOException {
  String templatePath = request.getServletContext().getRealPath("") + "/template/税源信息比对.docx";
  String fileName = new String("税源信息比对".getBytes("gb2312"), "ISO8859-1") + ".docx";
  /*数据*/
  Map<String, Object> params = new HashMap<String, Object>();
  params.put("${name}", "aaaa");
  params.put("${sex}", "bbbb");
 
  TempleWordUtil wordUtil = new TempleWordUtil();
 
  XWPFDocument doc;
  InputStream is = new FileInputStream(templatePath);
 // is = getClass().getClassLoader().getResourceAsStream(templatePath);
  doc = new XWPFDocument(is);  //只能使用.docx的
 
  wordUtil.replaceInPara(doc, params);
  //替换表格里面的变量
  wordUtil.replaceInTable(doc, params);
  OutputStream os = response.getOutputStream();
 
  response.setContentType("application/vnd.ms-excel");
  response.setHeader("Content-disposition", "attachment;filename=" + fileName);
 
  doc.write(os);
 
  wordUtil.close(os);
  wordUtil.close(is);
 
  os.flush();
  os.close();
 
}

TempleWordUtil 工具类

?
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
import org.apache.poi.xwpf.usermodel.*;
  
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;
 
/**
 * 写入word工具类
 * @author z
 *
 */
public class TempleWordUtil {
 
  /**
   * 替换段落里面的变量
   *
   * @param doc  要替换的文档
   * @param params 参数,导入的数据
   */
  public void replaceInPara(XWPFDocument doc, Map<String, Object> params) {
    Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
    XWPFParagraph para;
    while (iterator.hasNext()) {
      para = iterator.next();
      this.replaceInPara(para, params);
    }
  }
  
  /**
   * 替换段落里面的变量
   *
   * @param para  要替换的段落
   * @param params 参数
   */
  public void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
    List<XWPFRun> runs;
    //Matcher matcher;
    if (this.matcher(para.getParagraphText()).find()) {
      runs = para.getRuns();
  
      int start = -1;
      int end = -1;
      String str = "";
      for (int i = 0; i < runs.size(); i++) {
        XWPFRun run = runs.get(i);
        String runText = run.toString();
        if ('$' == runText.charAt(0)&&'{' == runText.charAt(1)) {
          start = i;
        }
        if ((start != -1)) {
          str += runText;
        }
        if ('}' == runText.charAt(runText.length() - 1)) {
          if (start != -1) {
            end = i;
            break;
          }
        }
      }
  
      for (int i = start; i <= end; i++) {
        para.removeRun(i);
        i--;
        end--;
      }
  
      for (String key : params.keySet()) {
        if (str.equals(key)) {
          para.createRun().setText((String) params.get(key));
          break;
        }
      }
  
  
    }
  }
  
  /**
   * 替换表格里面的变量
   *
   * @param doc  要替换的文档
   * @param params 参数
   */
  public void replaceInTable(XWPFDocument doc, Map<String, Object> params) {
    Iterator<XWPFTable> iterator = doc.getTablesIterator();
    XWPFTable table;
    List<XWPFTableRow> rows;
    List<XWPFTableCell> cells;
    List<XWPFParagraph> paras;
    while (iterator.hasNext()) {
      table = iterator.next();
      rows = table.getRows();
      for (XWPFTableRow row : rows) {
        cells = row.getTableCells();
        for (XWPFTableCell cell : cells) {
          paras = cell.getParagraphs();
          for (XWPFParagraph para : paras) {
            this.replaceInPara(para, params);
          }
        }
      }
    }
  }
  
  /**
   * 正则匹配字符串
   *
   * @param str
   * @return
   */
  private Matcher matcher(String str) {
    Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(str);
    return matcher;
  }
  
  /**
   * 关闭输入流
   *
   * @param is
   */
  public void close(InputStream is) {
    if (is != null) {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
  /**
   * 关闭输出流
   *
   * @param os
   */
  public void close(OutputStream os) {
    if (os != null) {
      try {
        os.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐