C# 獲取Excel的指定單元格的值

深海藍山發表於2016-12-17

獲取Excel指定單元格示例

 ///<summary>
        /// 獲取指定檔案的指定單元格內容
        ///</summary>
        /// <param name="fileName">檔案路徑</param>
        /// <param name="row">行號</param>
        /// <param name="column">列號</param>
        /// <returns>返回單元指定單元格內容</returns>
        public string getExcelOneCell(string fileName, int row, int column)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook wbook = app.Workbooks.Open(fileName, Type.Missing, Type.Missing,
                 Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                 Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                 Type.Missing, Type.Missing);

            Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)wbook.Worksheets[1];

            string temp = ((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[row, column]).Text.ToString();

            wbook.Close(false, fileName, false);
            app.Quit();
            NAR(app);
            NAR(wbook);
            NAR(workSheet); 
            return temp;

        }

        //此函式用來釋放物件的相關資源
        private void NAR(Object o)
        {
            try
            {
                //使用此方法,來釋放引用某些資源的基礎 COM 物件。 這裡的o就是要釋放的物件
                System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
            }
            catch { }
            finally
            {
                o = null; GC.Collect();
            }
        }

呼叫示例:

//獲取指定單元格示例(獲取第三行第二列的值)
string str = getExcelOneCell(@"F:\67250464X9.xls", 3, 2);

若是批量取多個Excel的指定單元格值,則用程式獲取資料夾下所有Excel,迴圈呼叫此方法即可

相關文章