In the past, I used C # To directly operate Excel, but found that the performance was extremely low. Recently, I found that using macros in Excel can quickly complete the batch processing function, so I decided to write a program using C # To create a macro for an Excel file. The project is as follows:
Code
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