using System.Data; using ExcelDataReader;
using System; using System.IO; using System.Data; using System.Text; using ExcelDataReader; namespace XlsReader { class Program { static public string AppPath; static int Main(string[] args) { DataSet ds; AppPath = AppDomain.CurrentDomain.BaseDirectory; if (args.Length > 0) { string file = Path.Combine(AppPath, args[0]); if (File.Exists(file)) { var extension = Path.GetExtension(file).ToLower(); Console.WriteLine("讀取檔案:" + file); using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { //判斷格式套用讀取方法 IExcelDataReader reader = null; if (extension == ".xls") { Console.WriteLine(" => XLS格式"); reader = ExcelReaderFactory.CreateBinaryReader(stream , new ExcelReaderConfiguration() { FallbackEncoding =Encoding.GetEncoding("big5") }); } else if (extension == ".xlsx") { Console.WriteLine(" => XLSX格式"); reader = ExcelReaderFactory.CreateOpenXmlReader(stream); } else if (extension == ".csv") { Console.WriteLine(" => CSV格式"); reader = ExcelReaderFactory.CreateCsvReader(stream, new ExcelReaderConfiguration() { FallbackEncoding = Encoding.GetEncoding("big5") }); } else if (extension == ".txt") { Console.WriteLine(" => Text(Tab Separated)格式"); reader = ExcelReaderFactory.CreateCsvReader(stream, new ExcelReaderConfiguration() { FallbackEncoding = Encoding.GetEncoding("big5"), AutodetectSeparators = new char[] { '\t' } }); } //沒有對應產生任何格式 if (reader == null) { Console.WriteLine("未知的處理檔案:" + extension); Console.ReadKey(); return 20; } Console.WriteLine(" => 轉換中"); using (reader) { ds = reader.AsDataSet(new ExcelDataSetConfiguration() { UseColumnDataType = false, ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration() { //設定讀取資料時是否忽略標題 UseHeaderRow = false } }); //把 DataSet 顯示出來 var table = ds.Tables[0]; for(int row = 0; row < table.Rows.Count; row++) { for (var col = 0; col < table.Columns.Count; col++) { string data = table.Rows[row][col].ToString(); Console.Write(data + ","); } Console.WriteLine(""); } } } Console.WriteLine("結束...按任意鍵離開..."); Console.ReadKey(); return 0; } else { Console.WriteLine("檔案 " + file + " 不存在!"); Console.ReadKey(); return 18; } } else { Console.WriteLine("沒有提供參數!"); Console.ReadKey(); return 13; } } } }