POI读写word文档的内容



POI读写word文档的内容

public static void readwriteWord() {

// 读取word模板
FileInputStream in = null;
try
{
in = new FileInputStream(new File(fileName));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}

HWPFDocument hdt = null;
try {
hdt = new HWPFDocument(in);//得到word文档的信息

} catch (IOException e1) {
e1.printStackTrace();

}

// 读取word表格内容
try {
Range range = hdt.getRange();
// 得到文档的读取范围
TableIterator it2 = new TableIterator(range);
// 迭代文档中的表格

int tabCount = 0;
while (it2.hasNext()) {
// System.out.println(” 第几个表格 “+tabCount);
// System.out.println(num[tabCount] +” 行”);
Table tb2 = (Table) it2.next();
// 迭代行,默认从0开始
for(int i = 0; i < tb2.numRows(); i++) {
TableRow tr = tb2.getRow(i);
// System.out.println(” fu “+num[tabCount] +” 行”);
/*if (num[tabCount] < i && i < 7) {
tr.delete();
}*/
}

// end for
tabCount++;

}

// end while
Map<String, String> map = new HashMap<String,String>();
map.put(“需要替换的文字”, “替换后的文字”);

// 替换word表格内容
for (Map.Entry<String, String> entry : map.entrySet()) {
range.replaceText( entry.getKey().trim(),entry.getValue());
}

//System.out.println(“替换后————:”+range.text());
} catch (Exception e) {
e.printStackTrace();
}

ByteArrayOutputStream ostream = new ByteArrayOutputStream();
String pathAndName = path +”/”+ fileName;
File file = new File(pathAndName);
if (file.canRead()) {
file.delete();
}
FileOutputStream out = null;


try {
out = new FileOutputStream(pathAndName, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

try

{
hdt.write(ostream);
} catch (IOException e) {
e.printStackTrace();
}
// 输出字节流

try

{
out.write(ostream.toByteArray());
System.out.println(fileName + ” success”);
} catch (IOException e) {
e.printStackTrace();

}
try

{
out.close();

}

catch (IOException e) {
e.printStackTrace();
}

try {
ostream.close();
}

catch (IOException e) {

e.printStackTrace();
}

}