【发布时间】:2015-04-13 16:49:47
【问题描述】:
所以...基本上我有一个 docx 文件。而且我必须在几段中进行一些格式更改,然后保存在一个新文件中。我所做的基本上是跟随。
import scala.collection.JavaConversions._
import org.apache.poi.xwpf.usermodel._
def format( sourceDocumentPath: String, outputDocumentPath: String ) {
val sourceXWPFDocument = new XWPFDocument( new FileInputStream( sourcePath ) )
// lets say I have a list of paragraph numbers... I want to format
val parasToFormat = List( 2, 10, 15, 20 )
val allParagraphs = sourceXWPFDocument.getParagraphs
for ( ( paragraph, index ) <- allParagraphs.zipWithIndex ) {
if( parasToFormat.contains( index ) ) {
formatParagraph( paragraph )
}
}
val outputDocx = new FileOutputStream( new File( outputDocumentPath ) );
xwpfDocument.write( outputDocx )
outputDocx.close()
}
def formatParagraph( paragraph: XWPFParagraph ): Unit = {
// Do some color changing to few runs
// Add few runs with new text.
}
大部分情况下一切正常。输出 docx 在我的 Ubuntu 上的 LibreOffice 中可以正常打开。
但是,当我将此输出 docx 传输到 Windows 系统并尝试在 MS Word 中打开此输出 docx 时,我得到了无限(不断增长的)垃圾页面。
欢迎来自 Poi 社区的聪明人的任何猜测。
另外...我的一个猜测是 - 可能是文件中的行尾混淆了 MS Word。由于 Ubuntu 使用( LF - \n )行尾,而 Windows 使用( CRLF - \r\n )。如果这确实是问题...那我该如何解决呢?
虽然...我的代码在 Scala 中...我认为类似的情况也应该适用于 Java 代码...大多数 Poi 用户将在 Java 社区中...所以我也添加了 Java 标记。
【问题讨论】:
-
任何人都有一些猜测......??
-
您是否尝试过将行尾更改为 windows 版本?它会确认或否认您对行尾是问题的怀疑。这样一来,人们可以通过确认指出正确的道路,或者如果问题出在其他地方,也不会浪费时间走上错误的道路。
-
嗯...虽然我们知道
docx文件实际上是包含各种xmls 的zip 文件。现在......虽然我可以在所有 xml 文件中更改它。我不确定如何从这些修改后的xmls 中正确创建docx文件。这意味着......我们需要在写入文件输出流时以某种方式强制行结束。
标签: java scala apache-poi