C# 更新Excel

来源:互联网 发布:等离子数控切割机编程 编辑:程序博客网 时间:2024/06/01 08:04

需要添加连个COM链接库、

Microsoft Office 14.0 Object Library

Microsoft Excel  14.0 Object Library

       /// <summary>
        /// 更新Excel 的指定行指定列的内容
        /// </summary>
        /// <param name="templetFile">Excel 的路径</param>
        /// <param name="row">指定Row (Cell 下面固定的可修改)</param>
        /// <param name="value">需要更新的值</param>

public void UpdateExcel2(string templetFile, int row, string value)

        {
            if (!File.Exists(templetFile))
            {
                return;
            }
            Microsoft.Office.Interop.Excel.Application xApp = new Microsoft.Office.Interop.Excel.Application(); ;
            Microsoft.Office.Interop.Excel.Workbook xBook;
            Microsoft.Office.Interop.Excel.Worksheet xSheet;
            Microsoft.Office.Interop.Excel.Range rng2;
            try
            {
                xApp.Visible = false;
                xBook = xApp.Workbooks._Open(templetFile,
               Missing.Value, Missing.Value, Missing.Value, Missing.Value
               , Missing.Value, Missing.Value, Missing.Value, Missing.Value
               , Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1];
                rng2 = (Microsoft.Office.Interop.Excel.Range)xSheet.Cells[row, 2];
                rng2.Value = value;
                xBook.Save();
                xSheet = null;
                xBook = null;
            }
            catch (Exception)
            {
                xSheet = null;
                xBook = null;
            }
            finally
            {
                xApp.Quit();
                xApp = null;
                GC.Collect();
            }
        }