C# 更新Excel

需要添加连个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();

            }

        }

    原文作者:海天湖色
    原文地址: https://blog.csdn.net/fengsheng1991/article/details/78491310
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞