當然,這裡的方法也不是唯一,程式是萬萬變的~
先引用Office物件.
(你的電腦如果有裝Office,可以在C:\Program Files\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office12\找到,此為WIN 7的路徑。)
// 引用Excel物件 using Microsoft.Office.Interop.Excel; using Application = Microsoft.Office.Interop.Excel.Application;
選擇Excel檔案
// 引用Excel物件 private void button1_Click(object sender, EventArgs e) { // 自行建立的ExcelFile, 用來存放Excel的部份資訊 oExcelFile = new ExcelFile(); oExcelFile.HasHeaderRow = true; textBox1.Text = ""; // 選擇EXCEL的路徑 DialogResult result = openFileDialog1.ShowDialog(); if (result.ToString() == "OK") { oExcelFile.Path = openFileDialog1.FileName; textBox1.Text = openFileDialog1.FileName; } else { return; } }
開始讀取Excel裡的資訊,以下為簡單的範例
try { // 建立Excel物件 Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); // 將Excel資訊記在Workbook物件裡 Workbook oWorkbook = ExcelApp.Workbooks.Open(oExcelFile.Path, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false); // 建立Sheets物件, 用來存放Excel裡的每個頁籤 Sheets oSheets = oWorkbook.Worksheets; // 拿出第一個Sheet, 放在Worksheet物件裡 Worksheet worksheet = (Worksheet)oSheets.get_Item(1); // 找出列和行的範圍筆數 Range range = worksheet.UsedRange; oExcelFile.RowCount = range.Rows.Count; oExcelFile.ColCount = range.Columns.Count; // 開始抓出資料 for (int i = oExcelFile.StartRow; i <= oExcelFile.RowCount; i++) { // 自行建立的Fields物件, 用來存放Excel裡的欄位值 Fields oFields = new Fields(); // 將抓到的值放到Fields物件裡 oFields.NAME = ((Range)worksheet.Cells[i, 1]).Value2.ToString(); oFields.YEAR = ((Range)worksheet.Cells[i, 2]).Value2.ToString(); } // ... // 處理拿到手的Excel資訊 // ... } catch (Exception ex) { Console.WriteLine("Error:" + ex.Message); } finally { if (oSheets != null) { Marshal.FinalReleaseComObject(oSheets); } if (oWorkbook != null) { oWorkbook.Close(false); Marshal.FinalReleaseComObject(oWorkbook); } if (ExcelApp != null) { ExcelApp.Workbooks.Close(); ExcelApp.Quit(); Marshal.FinalReleaseComObject(ExcelApp); } }
提供ExcelFile物件供參考
public class ExcelFile { public string Path { get; set; } public int RowCount { get; set; } public int ColCount { get; set; } public bool HasHeaderRow { get; set; } public int StartRow { get { return HasHeaderRow ? 2 : 1; } } }
參考來源:黑暗執行緒
感謝您的分享,
回覆刪除請問若 office 找不到 PIA 這個路徑是否跟安裝版本有關 ?
沒錯~我的範例是用Office 2007的.
刪除