C#修改 Excel指定单元格的值

时间:2022-10-02 15:33:06

/// <summary>

/// 将指定字符串写入指定单元格中
/// </summary>
/// <param name="data">要写入的数据源</param>
/// <param name="sheetName">工作表名称(全路径+EXCEL表名称)</param>
/// <param name="row">第几行</param>
/// <param name="column">第几列</param>
public void WriteData(string data,string sheetName, int row, int column)
{
try
{

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//实例化Excel对象
object missing = System.Reflection.Missing.Value;//获取缺少的object类型值
//打开指定的Excel文件 
excel.Application.DisplayAlerts = false;//不显示提示对话框  

Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Open(sheetName,
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);//打开Excel 
Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Worksheets;//实例表格
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets[1];//第一个表格

worksheet.Cells[row,column].value = data;  
workbook.Save();//保存工作表
workbook.Close(false, missing, missing);//关闭工作表
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}

}