doc文档的读取,写入以及读取并写入(自己写的,亲测可用)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42321963/article/details/86288870
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();
		}
	}
}

 

展开阅读全文

没有更多推荐了,返回首页