问题描述
从 IDE 使用 Apache POI 的 I/O 工作正常,但是当将其导出到可运行的 JAR 中,然后将其包装在 exe 中时,输出结果只是问号。并且由于 XWPFDocument 仅写入到 OutputStream,因此无法明确指定编码。那么,有什么办法可以解决这个问题呢? 相关代码如下:
try (var WordOutput = new FileOutputStream(whichFile,true);
var MSDoc = new XWPFDocument(OPCPackage.open(whichFile));)
{ //inside try block Now
List<XWPFTable> tables = MSDoc.getTables();
tables.toArray();
var arabicRow = arabicTable.getRow(0);
arabicRow.getCell(1).removeParagraph(0);
//adding a paragraph with a right alignment:
XWPFParagraph arabicParagraph = arabicRow.getCell(1).addParagraph();
arabicParagraph.setAlignment(ParagraphAlignment.RIGHT);
CTP ctp = arabicParagraph.getCTP();
CTPPr ctppr;
if ((ctppr = ctp.getPPr()) == null) ctppr = ctp.addNewPPr();
ctppr.addNewBidi().setVal(true);
//a Run is the content of the paragraph,plus other properties.
XWPFRun arabicSentence = arabicParagraph.createRun();
String theString = "\u202E" + (arabic text here) + "\u202C";
MSDoc.write(WordOutput);
} catch(Exception e) {
//my exception handler
}
先谢谢你!
解决方法
好的,解决了! 问题是我再次将字符串从 UTF-8 编码为 UTF-8,这显然没有意义。我要留下这个答案,因为解决这个问题有点困难的原因是我的程序有 3 个组件。
- Apache POI(我一直怀疑它)。
- JavaFX
- Java(准确地说是 JVM)。 我将字符串从 TextArea 写入 word 文件,在另一个 bug 搜索期间,我将其编码为 UTF-8:
String theString = new String(theTextArea.getText().getBytes(),"UTF-8");
我已经解决了那个错误,但是这个构造函数看起来太漂亮了,我无法将其改回:
String theString = theTextArea.getText();
瞧,我运行程序来编译、导出它,一切正常,问题就解决了。我希望那些有这样问题的人能找到这个答案。我为我的愚蠢道歉,XD。