讀取TXT檔案內容,生成Excel檔案
阿新 • • 發佈:2019-01-25
需要用到jar檔案:poi-3.0.1.jar
package office; /** * 解析txt檔案,輸出到Excel檔案 * @author JavaAlpha * @date 2011-7-28 * @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.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; 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; public class WordReader { /** * @param args */ public static void main(String[] args) { readFileByLine("E:/1.txt"); } /** * 以行為單位讀取檔案(文字檔案) * * @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 */ 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); } } }