1. 程式人生 > >【轉】java將excel文件轉換成txt格式文件

【轉】java將excel文件轉換成txt格式文件

gets ade app jar包 flush csdn substr fontsize index

在實際應用中,我們難免會遇到解析excel文件入庫事情,有時候為了方便,需要將excel文件轉成txt格式文件。下面代碼裏面提供對xls、xlsx兩種格式的excel文件解析,並寫入到一個新的txt文件中,數據以分隔符逗號","隔開。

excel文件如圖所示:

技術分享圖片

轉換後的txt文件:

技術分享圖片

需要依賴4個jar包:

技術分享圖片

package com.xuan.excel;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * <p>版權所有:版權所有(C) 2014-2099</p> * ────────────────────────────────── * <p>作 者:青蓮劍仙</p> * ────────────────────────────────── * <p>將excel轉成TXT文本<p> *
*/ public class ExcelToTxt { private static File [] getFiles(String path){ File file = new File(path); // get the folder list File[] array = file.listFiles(); return array; } public static void main(String[] args) throws IOException { File[] files=getFiles("D:\\keyword"); for(int i=0;i<files.length;i++){ if (files[i].isFile()) { System.out.println("f=="+files[i].getPath()+" "+files[i].getName()); publishTxt(files[i].getPath()); } if (files[i].isDirectory()) { System.out.println("d=="+files[i].getPath()+" "+files[i].getName()); File[] files2=getFiles(files[i].getPath()); for(int j=0;j<files2.length;j++){ publishTxt(files2[j].getPath()); } } } } public static void publishTxt(String excelPath){ String columns[] = { "交易時間", "記賬日期", "銀行流水號", "商戶流水號", "訂單號", "訂單狀態", "付款方賬號/客戶號", "付款方戶名", "訂單金額", "交易金額", "手續費", "結算金額", "櫃臺代碼", "發卡行/通道", "支付卡種", "交易類型", "期數", "授權號", "項目號", "基本戶", "備註一", "備註二" }; Workbook wb = null; Sheet sheet = null; Row row = null; List<Map<String, String>> list = null; String cellData = null; String fileType=excelPath.substring(excelPath.indexOf(‘.‘) + 1); wb = readExcel(excelPath); if (wb != null) { // 用來存放表中數據 list = new ArrayList<Map<String, String>>(); // 獲取第一個sheet sheet = wb.getSheetAt(0); // 獲取最大行數 int rownum = sheet.getPhysicalNumberOfRows(); // 獲取第二行 row = sheet.getRow(1); // 獲取最大列數 int colnum = row.getPhysicalNumberOfCells(); for (int i = 0; i < rownum; i++) { Map<String, String> map = new LinkedHashMap<String, String>(); row = sheet.getRow(i); if (row != null) { for (int j = 0; j < colnum; j++) { cellData = (String) getCellFormatValue(row.getCell(j)); map.put(columns[j], cellData); } } else { break; } list.add(map); } } // 遍歷解析出來的list StringBuffer sb = new StringBuffer(); for (int i = 0; i < list.size(); i++) { for (Entry<String, String> entry : list.get(i).entrySet()) { String value = entry.getValue(); sb.append(value+","); } sb.append("\r\n"); } try { WriteToFile(sb.toString(), excelPath.replace(".xlsx", ".txt")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("*************EXCEL轉成TXT格式成功*************"); } // 讀取excel public static Workbook readExcel(String filePath) { Workbook wb = null; if (filePath == null) { return null; } String extString = filePath.substring(filePath.lastIndexOf(".")); InputStream is = null; try { is = new FileInputStream(filePath); if (".xls".equals(extString)) { return wb = new HSSFWorkbook(is); } else if (".xlsx".equals(extString)) { return wb = new XSSFWorkbook(is); } else { return wb = null; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return wb; } public static Object getCellFormatValue(Cell cell) { Object cellValue = null; if (cell != null) { // 判斷cell類型 switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: { cellValue = String.valueOf(cell.getNumericCellValue()); break; } case Cell.CELL_TYPE_FORMULA: { try{ // 判斷cell是否為日期格式 if (DateUtil.isCellDateFormatted(cell)) { // 轉換為日期格式YYYY-mm-dd cellValue = cell.getRichStringCellValue().getString();//cell.getDateCellValue(); } else { // 數字 cellValue =cell.getRichStringCellValue().getString(); //String.valueOf(cell.getNumericCellValue()); } }catch(Exception ex){} break; } case Cell.CELL_TYPE_STRING: { cellValue = cell.getRichStringCellValue().getString(); break; } default: cellValue = ""; } } else { cellValue = ""; } return cellValue; } /** * 生成文件 * @param str * @param filePath * @throws IOException */ public static void WriteToFile(String str, String filePath) throws IOException { BufferedWriter bw = null; try { FileOutputStream out = new FileOutputStream(filePath, true);// true,表示:文件追加內容,不重新生成,默認為false bw = new BufferedWriter(new OutputStreamWriter(out, "GBK")); bw.write(str += "\r\n");// 換行 bw.flush(); } catch (Exception e) { e.printStackTrace(); } finally { bw.close(); } } }

from:https://blog.csdn.net/usuallyuser/article/details/81217122

【轉】java將excel文件轉換成txt格式文件