#需要的dll Microsoft.Office.Interop.Excel (安装了office,都会找到这个dll)
//需要导入
using Microsoft.Office.Interop.Excel;
using System.Reflection;
//1.创建Applicaton对象
Microsoft.Office.Interop.Excel.Application xApp = new Microsoft.Office.Interop.Excel.Application();
//2.得到workbook对象,打开已有的文件
Workbook xBook = xApp.Workbooks.Open(filePath,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//3.指定要操作的Sheet
Worksheet xSheet = (Worksheet)xBook.Sheets[sheetName];
//cell单元格值得获取
string cellValue = ((Range)xSheet.Cells[rowNum, ColNum]).Text.ToString();
//cell单元格赋值
xSheet.Cells[rowNum, colNum] = cellValue;
//修改完后对 excel的保存
1. 不修改excel原文件,将此文件另存为 你想要的路径下面
xBook.Saved = true;
string lastPath = 另存为的路径;
xBook.SaveAs(lastPath);
2.直接修改原文件
string lastPath = 另存为的路径;
xBook.SaveAs(lastPath);
//关闭excel退出
xSheet = null;
xBook.Close();
//excel从内存中退出
xApp.Quit();
xApp = null;
再写完这些,做测试的时候,有时候明明将数据已经写入到excel中了,但是会出现没有的状态,看了看 后台还是有很多的excel进程。(建议KILL掉所有EXCEL进程,但是会导致关闭所有的excel档案,慎用!!)