当今很多第三方程序都能生成Excel文件(xls,xml,xlsx),
但用第三方程序只能读取标准格式的Excel文件,
读取非标准文件会出现:ERROR:Invalid file signature
最后采用MS Excel 方法:
引用组件:Interop.Excel.dll Interop.Office.dll
1 public class ExcelOffice 2 { 3 /// <summary> 4 /// 读取xls xml xlsx格式 5 /// </summary> 6 /// <param name="filePath"></param> 7 /// <returns></returns> 8 public static DataSet ReadExcelSheet(string filePath) 9 { 10 DataSet ds = null; 11 var app = new Excel.Application(); 12 var book = app.Workbooks.Open(filePath); 13 try 14 { 15 //读取sheet 16 int sheetsCount = book.Worksheets.Count;//获取sheet数量 17 if (sheetsCount <= 0) 18 { 19 return null; 20 } 21 ds = new DataSet(); 22 //遍历每一个sheet页面 23 for (int k = 1; k <= sheetsCount; k++) 24 { 25 Excel.Worksheet sheet = book.Worksheets.get_Item(k); 26 Excel.Range range = sheet.UsedRange; 27 28 int rowCount = range.Rows.Count;//获取行数 29 int columCount = range.Columns.Count;//获取列数 30 31 //设置列头 32 DataRow dr = null; 33 DataTable dt = new DataTable(sheet.Name); 34 for (int i = 1; i <= rowCount; i++) 35 { 36 if (i > 1) 37 { 38 dr = dt.Rows.Add(); 39 } 40 for (int j = 1; j <= columCount; j++) 41 { 42 //默认将第一行设置为datatable的标题 43 if (i == 1) 44 { 45 dt.Columns.Add(range.get_Item(i, j).Text); 46 } 47 else 48 { 49 dr[j - 1] = range.get_Item(i, j).Text; 50 } 51 } 52 } 53 } 54 } 55 catch (Exception ex) 56 { 57 throw ex; 58 } 59 finally 60 { 61 book.Close(); 62 app.Workbooks.Close(); 63 app.Quit(); 64 } 65 return ds; 66 } 67 }