package office;/** * 讀取Doc,Excel,PDF,html,產生Txt檔案,讀取Txt產生Excel檔案 * @author JavaAlpha * @date 2011-8-1 * @version V 1.0 */import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.Writer;import java.net.MalformedURLException;import java.net.URL;import java.util.HashMap;import java.util.Iterator;import java.util.Map;
import javax.swing.text.BadLocationException;import javax.swing.text.DefaultStyledDocument;import javax.swing.text.rtf.RTFEditorKit;
import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.pdfbox.pdfparser.PDFParser;import org.pdfbox.pdmodel.PDDocument;import org.pdfbox.util.PDFTextStripper;import org.textmining.text.extraction.WordExtractor;
public class ReadOffice {/** * @param args */public static void main(String[] args) {// readDoc("e:/1.doc");// readExcel("e:/1.xls");// readPDF("e:/1.pdf");// readHtml("e:/1.html");readHtmlAll("e:/1.html");}/** * 建立TXT檔案,寫入檔案內容 * * @param text */static void createTXTAndWriteDoc(String text, String path) {FileOutputStream fos = null;FileOutputStream out = null;try {// 建立一輸出檔案流,如果檔案存在先刪除檔案File f = new File(path);if (f.exists()) {f.delete();}fos = new FileOutputStream(f);out = new FileOutputStream(f);byte[] b = text.getBytes("GB2312");out.write(b);out.flush();System.out.println("檔案產生...");} catch (Exception e) {System.out.println("出現異常: " + e);} finally {try {if (null != fos) {fos.close();}} catch (IOException e) {e.printStackTrace();}try {if (null != out) {out.close();}} catch (IOException e) {e.printStackTrace();}fos = null;out = null;}}/** * 讀取DOC檔案 * * @param dir * @throws Exception */static void readDoc(String dir) {// 建立輸入資料流讀取doc檔案FileInputStream in = null;WordExtractor extractor = null;String text = null;try {in = new FileInputStream(new File(dir));// 建立WordExtractorextractor = new WordExtractor();// 對doc檔案進行提取text = extractor.extractText(in);System.out.println("text1:" + text);} catch (FileNotFoundException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();} finally {try {if (null != in) {in.close();}} catch (IOException e) {e.printStackTrace();}in = null;}// 寫入檔案內容createTXTAndWriteDoc(text, "e:/doc.txt");}/** * 讀取Excel檔案 * * @param dir */@SuppressWarnings("deprecation")static void readExcel(String dir) {/** * @param filePath * 檔案路徑 * @return 讀出的Excel的內容 */StringBuffer buff = new StringBuffer();try {// 建立對Excel活頁簿檔案的引用HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(dir));// 建立對工作表的引用。for (int numSheets = 0; numSheets < wb.getNumberOfSheets(); numSheets++) {if (null != wb.getSheetAt(numSheets)) {HSSFSheet aSheet = wb.getSheetAt(numSheets);// 獲得一個sheetfor (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet.getLastRowNum(); rowNumOfSheet++) {if (null != aSheet.getRow(rowNumOfSheet)) {HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 獲得一個行for (int cellNumOfRow = 0; cellNumOfRow <= aRow.getLastCellNum(); cellNumOfRow++) {if (null != aRow.getCell((short) cellNumOfRow)) {HSSFCell aCell = aRow.getCell((short) cellNumOfRow);// 獲得列值switch (aCell.getCellType()) {case HSSFCell.CELL_TYPE_FORMULA:break;case HSSFCell.CELL_TYPE_NUMERIC:buff.append(aCell.getNumericCellValue()).append(' ');break;case HSSFCell.CELL_TYPE_STRING:buff.append(aCell.getStringCellValue()).append(' ');break;}}}buff.append(' ');}}}}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}// 寫入檔案內容createTXTAndWriteDoc(buff.toString(), "e:/excel.txt");}/** * 讀取Powerpoint檔案 * * @param dir */static void readPPT(String dir) {}/** * 讀取PDF檔案 * * @param dir */static void readPDF(String dir) {String result = null;FileInputStream is = null;PDDocument document = null;try {is = new FileInputStream(dir);PDFParser parser = new PDFParser(is);parser.parse();document = parser.getPDDocument();PDFTextStripper stripper = new PDFTextStripper();result = stripper.getText(document);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (null != is) {try {is.close();} catch (IOException e) {e.printStackTrace();}}if (null != document) {try {document.close();} catch (IOException e) {e.printStackTrace();}}}// 寫入檔案內容createTXTAndWriteDoc(result, "e:/pdf.txt");}/** * // 讀取pdf檔案 * * @param file * @throws Exception */public void readPdf(String file) throws Exception {// 是否排序boolean sort = false;// pdf檔案名稱String pdfFile = file;// 輸入文字檔名稱String textFile = null;// 編碼方式String encoding = "GB2312";// 開始提取頁數int startPage = 1;// 結束提取頁數int endPage = Integer.MAX_VALUE;// 檔案輸入資料流,產生文字檔Writer output = null;// 記憶體中儲存的PDF DocumentPDDocument document = null;try {try {// 首先當作一個URL來裝載檔案,如果得到異常再從本地檔案系統//去裝載檔案URL url = new URL(pdfFile); // 注意參數已不是以前版本中的URL.而是File。document = PDDocument.load(pdfFile);// 擷取PDF的檔案名稱String fileName = url.getFile();// 以原來PDF的名稱來命名新產生的txt檔案if (fileName.length() > 4) {File outputFile = new File(fileName.substring(0, fileName.length() - 4) + ".txt");textFile = outputFile.getName();}} catch (MalformedURLException e) {// 如果作為URL裝載得到異常則從檔案系統裝載 //注意參數已不是以前版本中的URL.而是File。document = PDDocument.load(pdfFile);if (pdfFile.length() > 4) {textFile = pdfFile.substring(0, pdfFile.length() - 4) + ".txt";}}// 檔案輸入資料流,寫入檔案倒textFileoutput = new OutputStreamWriter(new FileOutputStream(textFile), encoding);// PDFTextStripper來提取文本PDFTextStripper stripper = null;stripper = new PDFTextStripper();// 設定是否排序stripper.setSortByPosition(sort);// 設定起始頁stripper.setStartPage(startPage);// 設定結束頁System.out.print(stripper.getText(document));stripper.setEndPage(endPage);// 調用PDFTextStripper的writeText提取並輸出文本stripper.writeText(document, output);} finally {if (output != null) {// 關閉輸出資料流output.close();}if (document != null) {// 關閉PDF Documentdocument.close();}}}/** * 讀取Txt檔案 * * @param filePath * @return * @throws Exception */public String getTextFromTxt(String filePath) throws Exception {FileReader fr = new FileReader(filePath);BufferedReader br = new BufferedReader(fr);StringBuffer buff = new StringBuffer();String temp = null;while ((temp = br.readLine()) != null) {buff.append(temp + " ");}br.close();return buff.toString();}/** * 讀取RTF檔案內容 * * @param filePath * @return */public String getTextFromRtf(String filePath) {String result = null;File file = new File(filePath);try {DefaultStyledDocument styledDoc = new DefaultStyledDocument();InputStream is = new FileInputStream(file);new RTFEditorKit().read(is, styledDoc, 0);result = new String(styledDoc.getText(0, styledDoc.getLength()).getBytes("ISO8859_1"));// 提取文本,讀取中文需要使用ISO8859_1編碼,否則會出現亂碼} catch (IOException e) {e.printStackTrace();} catch (BadLocationException e) {e.printStackTrace();}return result;}/** * @param filePath * 檔案路徑 * @return 獲得html的全部內容 */public static String readHtml(String filePath) {BufferedReader br = null;StringBuffer sb = new StringBuffer();try {br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "GB2312"));String temp = null;while ((temp = br.readLine()) != null) {sb.append(temp);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}// 寫入檔案內容createTXTAndWriteDoc(sb.toString(), "e:/html.txt");return sb.toString();}/** * @param filePath * 檔案路徑 * @return 獲得的html常值內容 */public static void readHtmlAll(String filePath) {// 得到body標籤中的內容String str = readHtml(filePath);StringBuffer buff = new StringBuffer();int maxindex = str.length() - 1;int begin = 0;int end;// 截取>和<之間的內容while ((begin = str.indexOf('>', begin)) < maxindex) {end = str.indexOf('<', begin);if (end - begin > 1) {buff.append(str.substring(++begin, end));}begin = end + 1;}// 寫入檔案內容createTXTAndWriteDoc(buff.toString(), "e:/htmlAll.txt");//return buff.toString();}/** * 以行為單位讀取檔案(文字檔) * * @param filePath */public static void readFileByLine(String filePath) {File file = new File(filePath);BufferedReader bd = null;Map<String, String> str = new HashMap<String, String>();String s1 = "";String s2 = "";try {bd = new BufferedReader(new InputStreamReader(new FileInputStream(file), "gb2312"));// 編碼轉換(關鍵的地方)String temp = "";int line = 1;while ((temp = bd.readLine()) != null) {if (temp.length() > 0) {s1 = temp.substring(0, 3);s1 = s1.trim();s2 = temp.substring(4);s2 = s2.trim();str.put(s1, s2);}++line;}createExcel(str);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (bd != null)bd.close();} catch (IOException e) {e.printStackTrace();}}}/** * 輸出Excel檔案,輸出格式為多行兩列 * * @param map */@SuppressWarnings( { "deprecation", "unchecked" })static void createExcel(Map<String, String> map) {try {// 建立一輸出檔案流FileOutputStream fOut = new FileOutputStream("e:/2.xls");File file = new File("e:/2.xls");if (file.exists()) {file.delete();}// 建立新的Excel 活頁簿HSSFWorkbook workbook = new HSSFWorkbook();// 在Excel活頁簿中建一工作表,其名為預設值// 如要建立一名為"連絡人使用者名稱和電話"的工作表,其語句為:HSSFSheet sheet = workbook.createSheet("連絡人使用者名稱和電話");HSSFRow row = null;// 在索引0的位置建立儲存格(左上端)HSSFCell cell1 = null;HSSFCell cell2 = null;Iterator iter = map.entrySet().iterator();int i = 0;while (iter.hasNext()) {Map.Entry entry = (Map.Entry) iter.next();Object key = entry.getKey();Object val = entry.getValue();row = sheet.createRow((short) i++);cell1 = row.createCell((short) 0);cell2 = row.createCell((short) 1);// 定義儲存格為字串類型cell1.setCellType(HSSFCell.CELL_TYPE_STRING);cell2.setCellType(HSSFCell.CELL_TYPE_STRING);// 在儲存格中輸入一些內容cell1.setCellValue(key.toString());cell2.setCellValue(val.toString());if (i > 255) {break;}}// 把相應的Excel 活頁簿存檔workbook.write(fOut);fOut.flush();// 操作結束,關閉檔案fOut.close();System.out.println("檔案產生...");} catch (Exception e) {System.out.println("出現異常: " + e);}}}