網上搜索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;
}
}
}