第一种Excel文件就是Microsoft Office的。它的格式就是.xlsx等。我们要读其中内容,首先就是找着Microsoft.Office.Interop.Excel.dll和Office.dll两个dll文件。它一般是藏在C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office14中,依次找下去就可得到。在Visual Studio2012的步骤就是,先点击Solution Explorer中程序的reference--->Add Reference--->Browse--->就是刚才路径--->OK。其次就是using Excel = Microsoft.Office.Interop.Excel;最后就是写代码。如下所示,先新建Application,接着就是Workbook/Worksheet,最后就是读sheet的值了。
1 Excel.Application app = new Excel.Application(); 2 Excel.Workbook srcBook = app.Workbooks.Open(sourcePath); 3 4 FileStream fs = new FileStream("D://a.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); 5 StreamWriter sw = new StreamWriter(fs); 6 7 try 8 { 9 foreach (Excel.Worksheet sheet in srcBook.Worksheets) 10 { 11 for (int i = 1; i <= sheet.UsedRange.Rows.Count; i++) 12 { 13 for (int j = 1; j <= sheet.UsedRange.Columns.Count; j++) 14 { 15 if (sheet.Cells[i, j].Interior.Color != ColorTranslator.ToOle(Color.FromArgb(255, 204, 153))) 16 { 17 string src= sheet.Cells[i, j].Value == null ? string.Empty : sheet.Cells[i, j].Value.ToString(); 18 sw.WriteLine(src); 19 } 20 } 21 } 22 } 23 sw.WriteLine("END"); 24 } 25 catch (Exception ex) 26 { 27 throw ex; 28 } 29 finally 30 { 31 sw.Flush(); 32 sw.Close(); 33 app.Application.DisplayAlerts = false; 34 srcBook.Save(); 35 36 app.Quit(); 37 System.Runtime.InteropServices.Marshal.ReleaseComObject(app); 38 System.Runtime.InteropServices.Marshal.ReleaseComObject(srcBook); 39 app = null; 40 srcBook = null; 41 GC.Collect(); 42 }
第二种就是WPS Office的Excel文件。它的格式就是.xls等。它的过程类似如上。首先就是获得相应dll文件,如先Reference--->COM--->Type Libraries--->KingSoft ET2.0 ObjectLibrary.dll--->OK.其次就是Using ET;最后就是代码应用了。代码如下所示:
1 ET.Application app = new ET.Application(); 2 ET.workbook srcBook = new ET.workbook(); 3 srcBook = (ET.workbook)app.Workbooks.Open(sourcePath); 4 5 FileStream fs = new FileStream("D://a.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); 6 StreamWriter sw = new StreamWriter(fs); 7 8 try 9 { 10 foreach (ET.Worksheet sheet in srcBook.Worksheets) 11 { 12 for (int i = 1; i <= sheet.UsedRange.Rows.Count; i++) 13 { 14 for (int j = 1; j <= sheet.UsedRange.Columns.Count; j++) 15 { 16 if (sheet.Cells[i, j].Interior.Color != ColorTranslator.ToOle(Color.FromArgb(255, 204, 153))) 17 { 18 string src = sheet.Cells[i, j].Value == null ? string.Empty : sheet.Cells[i, j].Value.ToString(); 19 sw.WriteLine(src); 20 } 21 } 22 } 23 } 24 sw.WriteLine("END"); 25 } 26 catch (Exception ex) 27 { 28 throw ex; 29 } 30 finally 31 { 32 sw.Flush(); 33 sw.Close(); 34 app.Application.DisplayAlerts = false; 35 srcBook.Save(); 36 37 app.Quit(); 38 System.Runtime.InteropServices.Marshal.ReleaseComObject(app); 39 System.Runtime.InteropServices.Marshal.ReleaseComObject(srcBook); 40 app = null; 41 srcBook = null; 42 GC.Collect(); 43 }