java word2007_Java导出Word文档案例

package org.replace;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.util.Iterator;

import java.util.Map;

public class ReportWord {

public String replaceStr(String content, String

oldcontent,

String newcontent) {

String rc = encodeToUnicode(newcontent);

String target = "";

oldcontent = "$" + oldcontent + "$";

target = content.replace(oldcontent, rc);

return target;

}

public String encodeToUnicode(String str) {

if (str == null)

return "";

StringBuilder sb = new StringBuilder(str.length() * 2);

for (int i = 0; i < str.length(); i++) {

sb.append(encodeToUnicode(str.charAt(i)));

}

return sb.toString();

}

public String encodeToUnicode(char character) {

if (character > 255) {

return "" + (character &

0xffff) + ";";

} else {

return String.valueOf(character);

}

}

public void exportWordFile(String inputPath, String

outPath,

Map data)

{

String sourname = inputPath;

String sourcecontent = "";

InputStream ins = null;

try {

ins = new FileInputStream(sourname);

byte[] b = new byte[1638400];// 提高对文件的读取速度,特别是对于1M以上的文件

if (!new File(sourname).isFile()) {

System.out.println("源模板文件不存在");

return;

}

int bytesRead = 0;

while (true) {

bytesRead = ins.read(b, 0, 1638400);

if (bytesRead == -1) {

System.out.println("读取模板文件结束");

break;

}

sourcecontent += new String(b, 0, bytesRead);

}

} catch (Exception e) {

e.printStackTrace();

}

String targetcontent = "";

String oldText = "";

Object newValue;

try {

Iterator keys =

data.keySet().iterator();

int keysfirst = 0;

while (keys.hasNext()) {

oldText = (String) keys.next();

newValue = data.get(oldText);

String newText = (String) newValue;

if (keysfirst == 0) {

targetcontent = replaceStr(sourcecontent, oldText,

newText);

keysfirst = 1;

} else {

targetcontent = replaceStr(targetcontent, oldText,

newText);

keysfirst = 1;

}

}

FileWriter fw = new FileWriter(outPath, true);

PrintWriter out = new PrintWriter(fw);

if (targetcontent.equals("") || targetcontent == "") {

out.println(sourcecontent);

} else {

out.println(targetcontent);

}

out.close();

fw.close();

System.out.println(outPath + " 生成文件成功");

} catch (IOException e) {

e.printStackTrace();

}

}

}

测试代码为:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值