[函式庫] Microsoft.Office.Interop.Excel
在 C# 中如何讀取 Excel 檔呢,使用 Microsoft.Office.Interop.Excel 套件就可以拉
1
| using Excel = Microsoft.Office.Interop.Excel;
|
開啟 Excel
1 2 3
| ExcelApp = new Excel.Application(); object objOpt = System.Reflection.Missing.Value; Excel.WorkbookClass wbclass = (Excel.WorkbookClass)ExcelApp.Workbooks.Open(filepath, objOpt, false, objOpt, objOpt, objOpt, true, objOpt, objOpt, true, objOpt, objOpt, objOpt, objOpt, objOpt);
|
讀取 Excel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| Excel.Sheets sheets = wbclass.Worksheets; foreach (Excel.Worksheet sheet in sheets) { string SheetName = sheet.Name;
int RowsCount = sheet.UsedRange.Rows.Count; int ColsCount = sheet.UsedRange.Columns.Count; Excel.Range TopLeft = (Excel.Range)sheet.Cells[1, 1]; Excel.Range BottomRight = (Excel.Range)sheet.Cells[RowsCount, ColsCount]; Excel.Range range = (Excel.Range)sheet.get_Range(TopLeft, BottomRight); Array array = (Array)range.Cells.Value2;
for (int i = 1;i < RowsCount;i++) { for (int j = 1;j < RowsCount;j++) { Console.Write(array[i][j]); } } }
|
正確關閉 Excel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| if (sheets != null) { Marshal.FinalReleaseComObject(sheets); } if (wbclass != null) { wbclass.Close(false); Marshal.FinalReleaseComObject(wbclass); } if (ExcelApp != null) { ExcelApp.Workbooks.Close(); ExcelApp.Quit(); Marshal.FinalReleaseComObject(ExcelApp); }
|