以前一直是用C#直接操作Excel,但是發現性能無比低下,最近發現用Excel中的宏可以高速的完成批處理的功能,於是決定寫一個用C#為Excel文件創建宏的程序,工程如下:
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Text;
using Office = Microsoft.Office.Core;
using VBDE = Microsoft.Vbe.Interop;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
string MyFile = Path.GetFullPath(".") + @"sample.xls";
CreateWorkbook(MyFile,GetMacro());
Console.WriteLine("File Saved to " + MyFile);
Console.ReadLine();
}
#region Get Macro
private static string GetMacro()
{
StringBuilder sb = new StringBuilder();
sb.Append("Sub FormatSheet()" + " ");
sb.Append(" msgbox "http://www.cnblogs.com/huangcong/" ");
sb.Append("End Sub");
return sb.ToString();
}
#endregion
#region Create Workbook
private static void CreateWorkbook(string FileName,string Macro)
{
Excel.Application xl = null;
Excel._Workbook wb = null;
Excel._Worksheet sheet = null;
VBDE.VBComponent module = null;
bool SaveChanges = false;
try
{
if (File.Exists(FileName)) { File.Delete(FileName); }
GC.Collect();
xl = new Excel.Application();
xl.Visible = false;
wb = (Excel._Workbook)(xl.Workbooks.Add( Missin