項目涉及到要向一個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();
}
}