需求:
因为Excel中数据量很大,其中包含了几个宏程序从其他数据源读取数据,运行一次宏需要比较长的时间,为了不影响使用,要求每天半夜运行一次Excel中的宏(无参数),Excel存放在共盘上。
解决方案:
Sharepoint上写了一个Timejob,Timejob每天去运行宏。
写Timejob参考http://www.cnblogs.com/batter152/p/4705316.html
在运行时会碰到的问题
ERROR – RETRIEVING THE COM CLASS FACTORY FOR COMPONENT WITH CLSID {00020812-0000-0000-C000-000000000046} FAILED DUE TO THE FOLLOWING ERROR: 80070005 ACCESS IS DENIED. (EXCEPTION FROM HRESULT: 0X80070005 (E_ACCESSDENIED)).
或者报错没有权限,或者报错说
Microsoft Excel cannot access the filee are several possible reasons:• The file name or path does not exist. • The file is being used by another program. • The workbook you are trying to save has the same name as a currently open workbook.
通过做下面两个步骤就可以解决:
1.创建桌面快捷方式
需要手动创建文件夹,把Excel运行快捷方式放到这个文件夹下面
64位系统: C:\Windows\SysWOW64\config\systemprofile\Desktop
32为系统: C:\Windows\System32\config\systemprofile\Desktop
2.修改运用程序的权限
64位系统运行dcomcnfg
32位系统运行mmc -32,然后添加Component services
展开Services –> Computers –> My Computer –> DCOM Config如下图,这个账号是IIS80端口Application Pool的账号
找到Microsoft Excel Application CLSID {00020812-0000-0000-C000-000000000046}
点Security Tab修改,点Identity Tab 修改分别如下
也可以把默认修改一下,右击My Computer
附上C#运行宏程序的代码如下
引用
using Excel = Microsoft.Office.Interop.Excel;
//using Microsoft.Office.Core;
DLL: Microsoft.Office.Interop.Excel
并且设置dll属性Embed Interop Types为False,不然也会报错
1.使用方法
protected void Page_Load(object sender, EventArgs e) { try { // 返回对象 object objRtn = new object(); // 获得一个ExcelMacroHelper对象 // 执行指定Excel中的宏,执行时显示Excel SPSecurity.RunWithElevatedPrivileges(delegate() { //RunMoc(@"C:\Library\test.xlsm", "ThisWorkbook.getTime", null, out objRtn, false); string source = @"\\xxxxx\Test\TEST.xlsm"; string destination = @"C:\Library\TEST.xlsm"; //File.Copy(destination,source,true); RunMoc(source, "TEST.xlsm!TEST.test", null, out objRtn, false); }); } catch (System.Exception ex) { lb_error.Text = ex.Message; } }
2.运行方法
/// <summary> /// 执行Excel中的宏 /// </summary> /// <param name="excelFilePath">Excel文件路径</param> /// <param name="macroName">宏名称</param> /// <param name="parameters">宏参数组</param> /// <param name="rtnValue">宏返回值</param> /// <param name="isShowExcel">执行时是否显示Excel</param> public void RunMoc(string excelFilePath,string macroName,object[] parameters,out object rtnValue,bool isShowExcel) { // 创建Excel对象示例 Excel.ApplicationClass oExcel = new Excel.ApplicationClass(); try { // 检查文件是否存在 if (!File.Exists(excelFilePath)) { throw new System.Exception(excelFilePath + " 文件不存在"); } #region 调用宏处理 // 准备打开Excel文件时的缺省参数对象 object oMissing = System.Reflection.Missing.Value; // 根据参数组是否为空,准备参数组对象 object[] paraObjects; if (parameters == null) { paraObjects = new object[] { macroName }; } else { // 宏参数组长度 int paraLength = parameters.Length; paraObjects = new object[paraLength + 1]; paraObjects[0] = macroName; for (int i = 0; i < paraLength; i++) { paraObjects[i + 1] = parameters[i]; } } // 判断是否要求执行时Excel可见 if (isShowExcel) { // 使创建的对象可见 oExcel.Visible = true; } // 创建Workbooks对象 Excel.Workbooks oBooks = oExcel.Workbooks; // 创建Workbook对象 Excel._Workbook oBook = null; // 打开指定的Excel文件 oBook = oBooks.Open( excelFilePath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing ); // 执行Excel中的宏 rtnValue = this.RunMacro(oExcel, paraObjects); // 保存更改 oBook.Save(); // 退出Workbook oBook.Close(false, oMissing, oMissing); #endregion // 释放Workbook对象 System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook); oBook = null; // 释放Workbooks对象 System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks); oBooks = null; } catch (Exception ex) { throw ex; } finally { // 关闭Excel oExcel.Quit(); // 释放Excel对象 System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel); oExcel = null; // 调用垃圾回收 GC.Collect(); } } /// <summary> /// 执行宏 /// </summary> /// <param name="oApp">Excel对象</param> /// <param name="oRunArgs">参数(第一个参数为指定宏名称,后面为指定宏的参数值)</param> /// <returns>宏返回值</returns> private object RunMacro(object oApp, object[] oRunArgs) { try { // 声明一个返回对象 object objRtn; // 反射方式执行宏 objRtn = oApp.GetType().InvokeMember( "Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, oApp, oRunArgs ); // 返回值 return objRtn; } catch (Exception ex) { // 如果有底层异常,抛出底层异常 if (ex.InnerException.Message.ToString().Length > 0) { throw ex.InnerException; } else { throw ex; } } }
3.VBA代码,模块名字是TEST
Sub test() With ThisWorkbook.Sheets("sheet1") n = .Cells(11111, 2).End(xlUp).Row + 1 .Cells(n, 2) = Time .Cells(n, 3) = Date End With End Sub