java - 如何在java中的.doc文件中使用POI hwpfdocument写入大量文本

标签 java apache-poi

我是 POI API 的新手,因此,每当我使用 HWPFDocument 类在 HWPF 文档创建的 .doc 文件中写下文本时,生成的 doc 文件只有一个字母而不是整个文本,我写了。

因此,请给出我如何向其中添加更多文本的答案。

这是代码:

/**
             *  Create a POIFSFileSystem from an InputStream.
             *  Test.doc is an empty doc with no contents
             */
            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("test.doc"));

            /**
             * Horrible word Document Format
             */
            HWPFDocument hwpfDocument = new HWPFDocument(fs);
            /**
             * range is used for getting the range of the document except header and footer
             */

            Range range = hwpfDocument.getRange();
            range.numParagraphs();
            /**
             * creating Paragraph
             */
            /**
             *  Inserts a paragraph into the end of this range.
             *  ParagraphProperties -> for creating Paragraph, index of the paragraph
             */
            /*Paragraph paragraph1 = range.insertBefore(new ParagraphProperties(), 0);

            paragraph1.setJustification((byte) 0); // 0-left, 1-center, 2-right, 3-left and right*/
            CharacterRun characterRun1 =  range.insertBefore("Document");
            /**
             * setting the font size
             */
            characterRun1.setFontSize(2 * 12); // takes as an argument half points
            /**
             * making Text Bold Italic
             */
            characterRun1.setBold(true);
            characterRun1.setItalic(true);
            characterRun1.setColor(111);
            characterRun1.setData(true);
            //characterRun1.replaceWith("Document");

            hwpfDocument.write(new FileOutputStream("hpwf-create-doc.doc", true));

最佳答案

如果可以,从使用 HWPFDocument 切换到 XWPFDocument(生成 .docx 而不是 .doc)。 .docx 格式在底层更明智(它基于 XML 而不是二进制),因此 POI 通常用它做得更好。

否则,请尝试使用更简单的模板文档。 word 文件格式对各种位都非常挑剔,您可能遇到过这样的情况,即 POI 不知道需要更新文件中的某些内容,然后 word 默默反对。

关于java - 如何在java中的.doc文件中使用POI hwpfdocument写入大量文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6149298/

相关文章:

java - 如何设置固定列宽值(以英寸为单位)。 Apache 兴趣点

java - Spring MVC 应用程序在 Eclipse 中运行但不在 Intellij 中运行 - 找不到 404

方法中不相关泛型的 Java 删除错误

java - 如何为每个泛型类型创建一个新的 bean 实例?

java - 实例化非最终静态变量是线程安全的吗?

java - XSSF 无法复制样式 (POI)

java - 使用 Apache-POI 自动格式化 Word

java - 加密文件或字符串安全 android

java - Apache-POI:无法写入现有工作簿

java - excel poi : apply foreground color to blank cells