VSTO学习之路:学习使用Epplus——读写VBA代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VSTO学习之路:学习使用Epplus——读写VBA代码相关的知识,希望对你有一定的参考价值。

创建xlsm工作簿:

宏工作簿,必须有VBProject对象,至少要有一个工作表

1 string path = @"E:\studyvs\open xml\test.xlsm";
2 var package = new ExcelPackage();
3 package.Workbook.Worksheets.Add("Sheet1");
4 //创建工程对象
5 package.Workbook.CreateVBAProject();
6 //保存工作簿
7 package.SaveAs(new FileInfo(path));
8 System.Windows.Forms.MessageBox.Show("创建成功");

向宏文件写入代码:

 1 string path = @"E:\studyvs\open xml\test.xlsm";
 2 var package = new ExcelPackage();
 3 package.Workbook.Worksheets.Add("Sheet1");
 4 //创建工程对象
 5 package.Workbook.CreateVBAProject();
 6 //也可以using OfficeOpenXml.VBA
 7 OfficeOpenXml.VBA.ExcelVbaProject proj = package.Workbook.VbaProject;
 8 //sheet1工作表模块
 9 OfficeOpenXml.VBA.ExcelVBAModule sheetmodule =proj.Modules["Sheet1"];
10 //为sheet1模块命名,和工作表名称一致
11 sheetmodule.Name = "sheet1";
12 sheetmodule.Code += "\r\nPrivate Sub Worksheet_SelectionChange(ByVal Target As Range)";
13 sheetmodule.Code += "\r\nMsgBox(\"Test of the VBA Feature!\")\r\nEnd Sub\r\n";
14 
15 
16 //工作簿模块
17 OfficeOpenXml.VBA.ExcelVBAModule workbookmodule = package.Workbook.CodeModule;
18 workbookmodule.Name = "workbook";
19 //给工作簿模块添加代码
20 workbookmodule.Code += "\r\nPrivate Sub Workbook_Open()\r\nsheet1.Cells(1,1).Value = \"VBA test\"";
21 workbookmodule.Code += "\r\nMsgBox \"VBA is running!\"\r\nEnd Sub";
22 
23 //创建一个标准模块
24 var m = package.Workbook.VbaProject.Modules.AddModule("Module1");
25 m.Code += "Public Sub Test(param1 as string)\r\n\r\nEnd sub\r\n";
26 m.Code += "Public Function functest() As String\r\n\r\nEnd Function\r\n";
27 
28 //创建两个类模块
29 var c = package.Workbook.VbaProject.Modules.AddClass("Class1", false);
30 c.Code += "Private Sub Class_Initialize()\r\n\r\nEnd Sub\r\nPrivate Sub Class_Terminate()\r\n\r\nEnd Sub";
31 var c2 = package.Workbook.VbaProject.Modules.AddClass("Class2", true);
32 c2.Code += "Private Sub Class_Initialize()\r\n\r\nEnd Sub\r\nPrivate Sub Class_Terminate()\r\n\r\nEnd Sub";
33 
34 //设置工程的访问密码
35 proj.Protection.SetPassword("EPPlus");
36 
37 //保存工作簿
38 package.SaveAs(new FileInfo(path));
39 System.Windows.Forms.MessageBox.Show("写入成功");

 对于已存在的test.xlsm文件,另存为test2.xlsm

1 string path = @"E:\studyvs\open xml\test.xlsm";
2 var package = new ExcelPackage(new FileInfo(path));
3 package.SaveAs(new FileInfo(@"E:\studyvs\open xml\test2.xlsm"));

 读取test.xlsm中各个模块的代码,写入文本文件

1 string path = @"E:\studyvs\open xml\test.xlsm";
2 var package = new ExcelPackage(new FileInfo(path));
3 foreach (var module in package.Workbook.VbaProject.Modules)
4 {
5     File.WriteAllText(string.Format(@"E:\studyvs\open xml\{0}.txt", module.Name), module.Code);
6 }
7 
8 System.Windows.Forms.MessageBox.Show("ok");

 

以上是关于VSTO学习之路:学习使用Epplus——读写VBA代码的主要内容,如果未能解决你的问题,请参考以下文章

有C#基础学习VBA还是VSTO哪个更容易和有效

Excel催化剂开源第16波-VSTO开发之脱离传统COM交互以提升性能

VSTO Outlook 约会事件 (VB.NET)

Hadoop学习之路HDFS的读写详解

day1::(python-学习之路)-流程控制和文件读写

[原]使用EPPlus读写xlsx文件