結果集容器初始化之后,要做的就是從文檔模板中讀取所有需要替換的標簽文本,并一一與容器中的數據項進行對應,繼而進行替換,追回將替換完畢的文檔另存為新的Word文檔。代碼6是另存Word文檔的主要代碼。
代碼6 另存Word文檔
文件名:DocBuilder.java
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
//讀取模板和輸出信息,調用保存模塊
public void saveAs(String tempPath, String outPath) {
__saveAs(tempPath+getTemplate(), outPath+getOutput() );
}
//替換模板并保存輸出
private void __saveAs(String tempFilePath, String outFilePath) {
if(mWordUtil.connect(false) == false) {
return;
//打開文檔模板
if(mWordUtil.open(tempFilePath) == false) {
mWordUtil.disconnect();
//獲取文檔模板中所有標簽文本
HashSet<String> texts = mWordUtil.getTagText(TAG_LEFT, TAG_RIGHT);
if(texts == null) {
mWordUtil.close();
//解析標簽文本并進行替換
Iterator<String> it = texts.iterator();
while(it.hasNext() ) {
TagParser parser = new TagParser(it.next() );
switch(parser.getType() ) {
case TagParser.TAG_TYPE_RS: {
handleRsTag(parser);
break;
default: {
//另存文檔
try {
mWordUtil.saveAs(outFilePath);
} catch(Exception e) {
e.printStackTrace();
FooDebug.getInstance().println("文檔處理完畢!");
代碼7是替換標簽文本的關鍵代碼。
代碼7 替換標簽文本
//處理數據集標簽(本數據集外)
private void handleRsTag(TagParser parser) {
//獲取標簽文本中的數據源和行列信息
final String dsId = parser.getItem1();
final int row = Integer.parseInt(parser.getItem2() );
final int col = Integer.parseInt(parser.getItem3() );
//獲取對應數據源的記錄集
ArrayList<ArrayList<String>> rows = mResuleSet.get(DS_PREFIX+dsId);
if(rows == null) {
String val = "";
//獲取標簽文本對應的列值
if( (row < rows.size()) && (col < rows.get(0).size() ) ) {
val = rows.get(row).get(col);
} catch(IndexOutOfBoundsException e) {
//替換標簽文本
mWordUtil.replace(parser.getRawText(), val);
·2023年7月目錄 ·2023年6月目錄 ·2023年5月目錄 ·2023年4月目錄 ·2023年3月目錄 ·2023年2月目錄 ·2023年1月目錄 ·2022年12月目錄 ·2022年11月目錄 ·2022年10月目錄 ·2022年9月目錄 ·2022年8月目錄 ·2022年7月目錄 ·2022年6月目錄