需要添加连个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();
}
}
本文介绍了一种使用C#通过Microsoft Office Interop Excel库来更新指定Excel文件中特定行列单元格值的方法。此方法首先检查文件是否存在,然后利用Interop库打开Excel文件并更新指定位置的数据。
732

被折叠的 条评论
为什么被折叠?



