使用POI的hwpf操作word乱码

mirzlm mirzlm 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

public void testWord(String file,String newPath) {
//File file = new File(fileString);
try {
FileInputStream in = new FileInputStream(file);
POIFSFileSystem pfs = new POIFSFileSystem(in);
HWPFDocument hwpf = new HWPFDocument(pfs);
Range range = hwpf.getRange();
StyleSheet styleSheet = hwpf.getStyleSheet();
TableIterator it = new TableIterator(range);
// 遍历一个DOC中的所有表格
while (it.hasNext()) {
Table tb = (Table) it.next();
// 遍历表格的行
for (int i = 0; i < tb.numRows(); i++) {
TableRow tr = tb.getRow(i);
// 遍历表格的列
for (int j = 0; j < tr.numCells(); j++) {
// 往表格中插入数据
TableCell td = tr.getCell(j);
String text = "哈哈,输入中文";
int p = td.numParagraphs();
Paragraph para = td.getParagraph(p);
ParagraphProperties pp = new ParagraphProperties();
if(j%2==0){
para.insertBefore(text);
}
}
}
}
// 在表格外面插入内容
CharacterProperties cp = new CharacterProperties();
cp.setBold(true);
cp.setCharacterSpacing(10);
cp.setChse(cp.SPRM_CHARSCALE);
cp.setCapitalized(true);
File outputFile = new File(newPath);
OutputStream output = new FileOutputStream(outputFile);
hwpf.write(output);
output.close();

} catch (Exception ex) {
ex.printStackTrace();
}

}


这是现在用的程序,我的需求是,先读取原来的word信息,包括文字、表格、样式等,然后再输入内容,再生成word文档。

可现在的问题很奇怪,我的原版word里有二个表,当第二个表中文多的话,生成的新word后面就会有乱码尾巴,第二个表中文越多,后面乱码就越多,汗死

为什么会有这个问题呢,不知道先辈们有没有遇到过

网上说,这个未解决中文问题,不知道为什么,我这个可以插入中文的

就是二个表或多个表了,就会有乱码,希望这里有哪位前辈遇到过类似的问题,与解决办法
...全文
评论 9
收藏 已收藏
分享
返回顶部
mirzlm
Java SE 62,621 成员 307,251 内容