网上搜索C#实现excel操作的示例太多了,但不知道有多少是经过验证确实可行才发布出来的,也是因为开发需要,我找了一些代码却发现大多都不能正确执行完毕,于是决定补充自己在实践中遇到的要点以供参考。如下示例:
using Microsoft.Office.Interop.Excel;
using System.Reflection;
public class MyConsole
{
public static void Main()
{
Application app = new ApplicationClass();
try
{
//让后台执行设置为不可见
app.Visible = false;
//新增加一个工作簿
Workbook wBook = app.Workbooks.Add(true);
//如果要打开已有的工作簿,则使用下面的注释语句
// Workbook wBook = app.Workbooks.Open(@"C:\YourPath\YourWorkbook.xls",
// missing, missing, missing, missing, missing, missing, missing,
// missing, missing, missing, missing, missing,missing, missing);
//取得一个工作表
//如果打开了已有的工作簿,也可以这样获取工作表Worksheet wSheet = wBook.ActiveSheet as Worksheet
Worksheet wSheet = wBook.Worksheets[1] as Worksheet;
wSheet.Cells[1, 1] = "this is a test";
//设置禁止弹出保存和覆盖的询问提示框
app.DisplayAlerts = false;
app.AlertBeforeOverwriting = false;
//保存工作簿
wBook.Save();
//保存excel文件
app.Save("C:\\abc.xls");
}
catch
{
}
finally
{
//确保Excel进程关闭
app.Quit();
app = null;
}
}
}