codecamp

Apache POI Word - 段落

在本章中,您将学习如何创建一个段落以及如何使用Java将其添加到文档中。 段落是Word文件中页面的一部分。

完成本章后,您将能够创建一个段落并对其执行读取操作。

创建段落

首先,让我们使用前面章节中讨论的引用类创建一个段落。 按照前面的章节,首先创建一个文档,然后我们可以创建一个段落。

以下代码段用于创建电子表格:

//Create Blank document
   XWPFDocument document= new XWPFDocument();
//Create a blank spreadsheet
   XWPFParagraph paragraph = document.createParagraph();

运行段落

您可以使用运行输入文本或任何对象元素。 使用Paragraph实例,您可以创建运行

以下代码段用于创建运行。

XWPFRun run=paragraph.createRun();

写入段落

让我们尝试在文档中输入一些文本。 考虑下面的文本数据:

At tutorialspoint.com, we strive hard to provide quality tutorials for self-learning purpose in the domains of Academics, Information Technology, Management and Computer Programming Languages.

以下代码用于将上述数据写入段落。

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class CreateParagraph 
{
   public static void main(String[] args)throws Exception 
   {
   //Blank Document
   XWPFDocument document= new XWPFDocument(); 
   //Write the Document in file system
   FileOutputStream out = new FileOutputStream(
   new File("createparagraph.docx"));
        
   //create Paragraph
   XWPFParagraph paragraph = document.createParagraph();
   XWPFRun run=paragraph.createRun();
   run.setText("At tutorialspoint.com, we strive hard to " +
   "provide quality tutorials for self-learning " +
   "purpose in the domains of Academics, Information " +
   "Technology, Management and Computer Programming
   Languages.");
   document.write(out);
   out.close();
   System.out.println("createparagraph.docx written successfully");
   }
}

将上述Java代码另存为 CreateParagraph.java ,然后从命令提示符处编译并运行它,如下所示:

$javac CreateParagraph.java
$java CreateParagraph

它将编译并执行以在当前目录中生成名为 createparagraph.docx 的Word文件,您将在命令提示符中获得以下输出:

createparagraph.docx written successfully

createparagraph.docx 文件如下所示。


Apache POI Word - 文件
Apache POI Word - 边框
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }