1. 程式人生 > >java 讀取word檔案

java 讀取word檔案

package com.example;


import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.FileInputStream;

public class wordPdf {

    public static void main(String[] args) {
        try{
            FileInputStream in = new FileInputStream("/Users/wangrongfei/Downloads/中國標準文獻分類號CCS.doc");// 載入文件
            POIFSFileSystem pfs = new POIFSFileSystem(in);
            HWPFDocument hwpf = new HWPFDocument(pfs);
            Range range = hwpf.getRange();// 得到文件的讀取範圍
            TableIterator it = new TableIterator(range);
            String[] stu = new String[5];
            // 迭代文件中的表格
            while (it.hasNext()) {
                Table tb = (Table) it.next();
                // 迭代行,預設從0開始
                for (int i = 0; i < tb.numRows(); i++) {
                    TableRow tr = tb.getRow(i);
                    // 迭代列,預設從0開始
                    for (int j = 0; j < tr.numCells(); j++) {

                        TableCell td = tr.getCell(j);// 取得單元格
                        // 取得單元格的內容
                        String s = "";
                        for (int k = 0; k < td.numParagraphs(); k++) {
                            Paragraph para = td.getParagraph(k);// 獲取第k個段落
                            s += para.text();
                            System.out.println(s);
                        }
                        s = s.replace("•", "");
                        stu[j] = s;

                        // end for
                    }// end for

                }
            }
        }catch (Exception e){

        }
    }
}