如何使用 Java 对齐 word 文档中的文本
问题描述
如何使用 Java 对齐 word 文档中的文本。
解决方案
以下是使用 Java 对齐 word 文档中的文本的程序。
import java.io.File; import java.io.FileOutputStream; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; public class AlignTextInWord { public static void main(String[] args)throws Exception { //空白文件 XWPFDocument document = new XWPFDocument(); //将文档写入文件系统 FileOutputStream out = new FileOutputStream(new File ("C:/poiword/alignparagraph.docx")); //创建段落 XWPFParagraph paragraph = document.createParagraph(); //将对齐段落设置为右对齐 paragraph.setAlignment(ParagraphAlignment.RIGHT); 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."); //创建另一个段落 paragraph = document.createParagraph(); //将对齐段落设置为中心 paragraph.setAlignment(ParagraphAlignment.CENTER); run = paragraph.createRun(); run.setText("The endeavour started by Mohtashim, an AMU " + "alumni, who is the founder and the managing director " + "of Tutorials Point (I) Pvt. Ltd. He came up with the " + "website tutorialspoint.com in year 2006 with the help" + "of handpicked freelancers, with an array of tutorials" + " for computer programming languages. "); document.write(out); out.close(); System.out.println("alignparagraph.docx written successfully"); } }
输出

java_apache_poi_word.html