doc文檔的讀取,寫入以及讀取並寫入(自己寫的,親測可用)

package com.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

/**
 * 
 * @author comeonzeze
 * 
 *
 */
public class Demo {
	public static void main(String[] args) {

		// String path="f:/a.doc"; readXWPF(path);

		// String path = "f:/b.doc"; createXWPF(path);

		/*
		 * String frompath="f:/a.doc"; String topath="f:/c.doc";
		 * readAndWriteXWPF(frompath, topath);
		 */

	}

	/**
	 * 從一個doc讀取,並寫入到另外一個doc
	 * 
	 * @param frompath
	 * @param topath
	 */
	public static void readAndWriteXWPF(String frompath, String topath) {
		try {
			// 讀取a.doc
			InputStream inp = new FileInputStream(frompath);
			XWPFDocument xd = new XWPFDocument(inp);
			// 目標doc
			XWPFDocument to_xd = new XWPFDocument();
			XWPFParagraph to_para = null;
			XWPFRun to_run = null;

			for (XWPFParagraph para : xd.getParagraphs()) {
				to_para = to_xd.createParagraph();
				for (XWPFRun run : para.getRuns()) {
					to_run = to_para.insertNewRun(0);
					to_run.setText(run.toString());
					System.out.println(run);
				}
			}
			try {
				OutputStream fileOut = new FileOutputStream(topath);
				to_xd.write(fileOut);
			} catch (Exception e) {
				e.printStackTrace();
			}

			xd.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 讀取doc,並打印在控制檯
	 * 
	 * @param path
	 *            String path = "f:/a.doc"; createXWPF(path);
	 */
	public static void readXWPF(String path) {
		try {
			InputStream inp = new FileInputStream(path);
			XWPFDocument xd = new XWPFDocument(inp);
			for (XWPFParagraph para : xd.getParagraphs()) {
				for (XWPFRun run : para.getRuns()) {
					System.out.println(run);
				}
			}
			xd.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 創建doc文檔
	 * 
	 * @param path
	 *            String path="f:/a.doc"; createXWPF(path);
	 * 
	 */
	public static void createXWPF(String path) {
		XWPFDocument xd = new XWPFDocument();
		XWPFParagraph para = xd.createParagraph();
		XWPFRun run = para.insertNewRun(0);
		run.setText("大家好,我是古天樂、");
		run.setText("大家好,我是張家輝");
		XWPFParagraph para1 = xd.createParagraph();
		run = para1.insertNewRun(0);
		run.setText("歡迎大家一起來玩貪玩藍月,和我一起闖關");
		try {
			OutputStream fileOut = new FileOutputStream(path);
			xd.write(fileOut);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章