1.判断电脑上是否安装Excel
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel");
return;
}
2.定义工作簿和工作表
Microsoft.Office.Interop.Excel.Workbooks workBooks = xlApp.Workbooks;//Workbooks代表一个 Microsoft Excel 工作簿
Microsoft.Office.Interop.Excel.Workbook workBook = workBooks.Open(template_Path+"template3.xlsx");
Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets[1];//取得sheet1
3.操作单元格的值
workSheet.Cells[3, 6].value = DateTime.Now.ToString("yyyy年M月d日");
4.关闭工作簿不保存,不显示警告提醒,不显示Excel
workBook.Close(false);
xlApp.DisplayAlerts = true;
xlApp.Visible = false;
5.退出excel,回收垃圾
xlApp.Quit();
GC.Collect();//强行销毁