利用替换法, 生成指定模板的 Word 文档 (Java)

利用替换法, 生成指定模板的 Word 文档 (Java)[@more@]

前天, 因女朋友公司需要, 需要把 3000 多记录的文本文件做成 Word 格式供打印, 其中文本文件每一行一条记录, 如下图所示:

数据格式截图: 利用 jacob 库生成 Word 文档的数据图片

目标 Word 文档格式截图: 利用 jacob 生成 Word 的模板图片

其中联系人统一改为某某负责人(收), 若为市或地区级的防疫站, 统一改为`计免科负责人(收)`, 否则为`防疫科负责人(收)`, 在上数据中, `卫生防疫站`都须替换为`疾病预防控制中心`.

为解决上述问题, 分三步:

1, 建立 Word 文档, 格式如图: 替换法生成 Word 中的源模板

2, 写 Java 程序, 利用替换法替换为有用的信息;

3, 开始替换, 以下为源代码:

Main.java

 
 

/**
* @(#) Main.java 2006-9-18
* Copyright 2006 Banny. All rights reserved.
*/
package edu.gdcc.banny;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
* @author Banny
*
*/
public class Main {

// 模板 Word 文档路径
private static final String TEMPLATE_FILE_PATH =
"E:/Workspaces/FormatDoc/FormatDoc/resource/template.doc";

// 每页的数量
private static final int SIZE_PER_PAGE = 14;

// 模板文档的页数
private static final int PAGE_MOUNT_OF_TEMPLATE = 100;

/**
* 主方法
*
* @param args
* 命令行参数, 每一个参数指定源 TXT 数据路径, 第二个参数指定生成 Word 的保存目标
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
if (args[0].equals("--help")) {
System.out
.println("edu.gdcc.banny.Main data-path"
+ " output-directory [template-pages] [debug]");
System.out
.println("edu.gdcc.banny.Main C:/data.TXT C:/output 100 true");
System.out
.println("其中 [debug], 当为 true 时, 打开 debug 功能");
return;
}
if (args.length < 2) {
System.err.println("参数错误! ");
return;
}

String path = args[0];// source database, txt format
String dest = args[1];// output directory
if (!dest.endsWith(File.separator))
dest = dest + File.separator;
int pages = PAGE_MOUNT_OF_TEMPLATE;// 模板文档的页数
if (args.length > 2)
pages = Integer.parseInt(args[2]);// 参数指定模板页数
boolean debug = false;// 默认 debug 关
if (args.length > 3)
debug = (args[3].equals("true")) ? true : false;

BufferedReader br = null;
WordBean word = null;
try {
br = new BufferedReader(new FileReader(
new File(path)));
int p = 0;
String line_ = null;
User user = null;
word = new WordBean(TEMPLATE_FILE_PATH);
word.openDoc();
while ((line_ = br.readLine()) != null) {
if (line_.startsWith("#"))// 当一行起始于 "#" 号时, 作为注释行
continue;
if (debug)
System.out.println(line_);
String line = line_.replaceAll(""", "");// 除去引号
p++;
if (p % (pages * SIZE_PER_PAGE) == 0) {
word.saveDoc(dest + (p - pages) + "-"
+ p + ".doc");
word.closeDoc();
word.openDoc(TEMPLATE_FILE_PATH);
} else {
String[] items = line.split(",");
String addr = items[4];// address
String sAddr = items[0];// specific format
String zip = items[3];// zipcode
user = new User();
user.setAddr(addr);
user.setSaddr(sAddr);
user.setZipcode(zip);
if (user.getAddr().length() > 19
|| user.getSaddr().length() > 19) {
continue;// 地址太长, 忽略
} else {
word.add(user);
}
}
}
word.saveDoc(dest + "last.doc");
word.closeDoc();
word = null;
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
br = null;
if (word != null) {
word.closeDoc();
word = null;
}
}
}
}

User.java

 
 

/**
* @(#) User.java 2006-9-18
* Copyright 2006 Banny. All rights reserved.
*/
package edu.gdcc.banny;

/**
* @author Banny
*
*/
public class User {

private static final String REGEX = ".*(省|自治区|新疆|阿勒泰|西藏|日喀则|"
+ "宁夏回族)*.*地区((卫生|)防疫站|疾病预防控制中心).*|"
+ ".*省*.*市((卫生|)防疫站|疾病预防控制中心).*";

private String zip;

private String addr;

private String sAddr;

public User() {
this(null, null, null);
}

public User(String zip, String addr, String sAddr) {
setZipcode(zip);
setAddr(addr);
setSaddr(sAddr);
}

public void setZipcode(String zip) {
this.zip = zip;
}

public String getZipcode() {
return zip;
}

public void setAddr(String addr) {
this.addr = addr;
}

public String getAddr() {
return addr;
}

public void setSaddr(String sAddr) {
this.sAddr = sAddr;
}

public String getSaddr() {
return sAddr.replace("卫生防疫站", "疾病预防控制中心");
}

public String getTarget() {
return (sAddr.matches(REGEX) ? "计免科" : "防疫科");
}

public String toString() {
return "地址: " + addr + "t" + "详细地址: " + sAddr
+ "t" + "邮编: " + zip;
}
}

WordBean.java

 
 

/**
* @(#) WordBean.java 2006-9-18
* Copyright 2006 Banny. All rights reserved.
*/
package edu.gdcc.banny;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
* @author Banny
*
*/
public class WordBean {

private static final String ZIP_TEMPLATE = "${zipcode}";

private static final String ADDR_TEMPLATE = "${addr}";

private static final String S_ADDR_TEMPLATE = "${s_addr}";

private static final String TARGET = "${target}";

private static final Variant V_FALSE = new Variant(
false);

private static final Variant V_TRUE = new Variant(true);

private static final Variant REPLACE = new Variant(1);

private static final Variant WRAP = new Variant(1);

private String path;

private boolean visible;

private static ActiveXComponent application;

private static Object appLock = new Object();

private Dispatch document;

private Dispatch selection;

private Dispatch find;

public WordBean() {
this(null);
}

public WordBean(String path) {
this(path, false);
}

public WordBean(String path, boolean visible) {
this.path = path;
this.visible = visible;
}

public void openDoc() {
openDoc(path);
}

public void openDoc(String path) {
if (path == null)
throw new NullPointerException(
"没有指定 Word 文档的路径");
openApp();
application.setProperty("Visible", new Variant(
visible));
document = Dispatch.invoke(
application.getProperty("Documents")
.toDispatch(),
"Open",
Dispatch.Method,
new Object[] { path, new Variant(false),
new Variant(true) }, new int[1])
.toDispatch();
selection = application.getProperty("Selection")
.toDispatch();
find = Dispatch.call(selection, "Find")
.toDispatch();
}

private static void openApp() {
if (application == null) {
synchronized (appLock) {
if (application == null) {
application = new ActiveXComponent(
"Word.Application");
}
}
}
}

public void saveDoc(String path) {
if (path.trim().equals(this.path.trim()))
throw new RuntimeException("目标文件不能与源文件为同一个文件");
Dispatch.call(document, "SaveAS", path);
}

public void closeDoc() {
Dispatch.call(document, "Close", new Variant(0));
closeApp();
}

private void closeApp() {
Dispatch.call(application, "Quit");
application = null;
document = null;
}

public void add(User user) {
String zip = user.getZipcode();
String addr = user.getAddr();
String s_addr = user.getSaddr();
String target = user.getTarget();
if (zip == null || zip.trim().equals("")
|| addr == null || addr.trim().equals("")
|| s_addr == null
|| s_addr.trim().equals("")) {
System.err.println(user);
return;
}
if (document == null)
throw new NullPointerException("没有打开文档");

Dispatch.call(find, "ClearFormatting");
Dispatch replacement = Dispatch.call(find,
"Replacement").toDispatch();
Dispatch.call(replacement, "ClearFormatting");

replace(ZIP_TEMPLATE, zip);
replace(ADDR_TEMPLATE, addr);
replace(S_ADDR_TEMPLATE, s_addr);
replace(TARGET, target);
}

private void replace(String oldStr, String newStr) {
Variant findText = new Variant(oldStr);
Variant replaceWith = new Variant(newStr);

Dispatch.callN(find, "Execute", new Variant[] {
findText, V_TRUE, V_FALSE, V_FALSE,
V_FALSE, V_FALSE, V_TRUE, WRAP, V_FALSE,
replaceWith, REPLACE });
}

}

附: 程序所用的包, 下载

注: 1, zip 文件中的 *.dll 文件放在 %JAVA_HOME%/bin 目录下

2, 由于 Blog 会过滤反斜杆, 所以源程序中可能会有一些差别

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/419718/viewspace-866544/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/419718/viewspace-866544/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值