java 用POI向word中写入文件

来源:互联网 发布:免备案php免费空间 编辑:程序博客网 时间:2024/05/17 13:42

项目涉及到要向一个word中插入一段文字,用到了apache的POI组件,可以很流畅地向已有word中写入文字。

(这里只是向word末尾加文字,不支持指定位置插入)

首先要下载apache POI的jar们,下载地址:https://poi.apache.org/download.html

这里要导入这些poi打头的jar,还要导入ooxml-lib中的xmlbeans这个jar。

(注意:这个word不能是正在被使用中的,不然会报错。)

下面是源代码:

import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.apache.poi.xwpf.usermodel.XWPFParagraph;import org.apache.poi.xwpf.usermodel.XWPFRun;import java.io.IOException;public class MTest {@SuppressWarnings("null")public static void main(String[] args) throws IOException {// TODO Auto-generated method stubInputStream is = new FileInputStream("D:\\aloha.docx");// 这里是你要写入的文件XWPFDocument xdoc = new XWPFDocument(is);// 创建一个段落XWPFParagraph xpara = xdoc.createParagraph();// 一个XWPFRun代表具有相同属性的一个区域。XWPFRun run = xpara.createRun();run.setBold(true); // 加粗run.setText("加粗的内容");run = xpara.createRun();run.setColor("FF0000");run.setFontSize(15);run.setText("插入内容。");OutputStream os = new FileOutputStream("D:\\aloha.docx");xdoc.write(os);os.close();}}

原创粉丝点击