Excel 调用vba宏导出

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using NPOI.SS.UserModel;
using System.Data;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.Linq;

namespace Sys.LXZX.Core.Utils
{
    /// <summary>
    /// 下载Excel帮助类
    /// </summary>
    public class ExcelDownHelper : System.Web.UI.Page
    {
        public string fileFullName = ""; // 文件路径+名称
        public string fileName = ""; //模板名称 
        public string fileDowName = ""; // 下载后的文件名称
        public string fileDowFullName = ""; // 下载文件路径+名称
        public string filePath = "";// 
        //构造函数
        public ExcelDownHelper(string filePath, string fileName, string fileDowName)
        {
            this.filePath = filePath;
            this.fileName = fileName;
            this.fileDowName = fileDowName;
            fileFullName = filePath + fileName;
            fileDowFullName = filePath + fileDowName;
            //File.Copy(@"E:\test.xls", fileFullName);
        }
        /// <summary>
        /// DataTable 数据写入Excel 
        /// </summary>
        /// <param name="dt">DataTable 数据</param>
        /// <param name="sheetName">表格名称</param>
        /// <param name="ishead">是否跳过头部</param>
        /// <param name="jump">数据跳过行数</param>
        public void TableToExcel(DataTable dt, string sheetName, bool ishead, int jump = 0)
        {

            if (File.Exists(fileDowFullName))
            { // 文件存在则删除
                File.Delete(fileDowFullName);
            }
            File.Copy(fileFullName, fileDowFullName); // copy结构
            IWorkbook workbook;
            FileStream fsRead = null;
            using (fsRead = File.OpenRead(fileDowFullName))
            {
                string fileExt = Path.GetExtension(fileDowFullName).ToLower();
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fsRead); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fsRead); } else { workbook = null; }
                if (workbook == null) { return; }
                //   ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName
                ISheet sheet;
                if (sheetName == "")
                {
                    sheet = workbook.GetSheet("Sheet1");
                }
                else
                {
                    sheet = workbook.GetSheet(sheetName.Trim());
                }
                if (ishead == false)  //  是否跳过表头
                {
                    //表头  
                    IRow row = sheet.GetRow(0);
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        ICell cell = row.CreateCell(i);
                        cell.SetCellValue(dt.Columns[i].ColumnName);
                    }
                }
                //数据  
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    IRow row1 = sheet.CreateRow(i + 1 + jump); // 数据从第几行开始写入
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        ICell cell = row1.CreateCell(j);
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                    }
                }
                //转为字节数组  
                MemoryStream stream = new MemoryStream();
                workbook.Write(stream);
                var buf = stream.ToArray();

                //保存为Excel文件  
                using (FileStream fs = new FileStream(fileDowFullName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buf, 0, buf.Length);
                    fs.Flush();
                }
            }
        }


        /// <summary>
        ///  下载文件()
        /// </summary>
        /// <param name="fileFullName">文件路径 包含文件名</param>
        /// <param name="downFileName">保存文件名(不包含路径)</param>
        /// <param name="isDeleteTempFile">true 下载后删除服务器文件  false 不删除</param>
        public void fileDownLoad(bool isDeleteTempFile)
        {
            FileInfo fileInfo = new FileInfo(fileDowFullName);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileDowName);
            HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            HttpContext.Current.Response.WriteFile(fileInfo.FullName);
            HttpContext.Current.Response.Flush();
            if (isDeleteTempFile == true)
            {
                File.Delete(fileDowFullName); // 下载完成后删除
            }
            HttpContext.Current.Response.End();
        }


        /// <summary>
        /// 执行Excel中的宏
        /// </summary>
        /// <param name="excelFilePath">Excel文件路径</param>
        /// <param name="macroName">宏名称</param>
        /// <param name="parameters">宏参数组</param>
        /// <param name="isShowExcel">执行时是否显示Excel</param>
        /// <returns>返回结果</returns>
        public object RunExcelMacro(string macroName, object[] parameters, bool isShowExcel)
        {
            object objRtn = new object();
            // 获得一个ExcelMacroHelper对象
            ExcelMacroHelper excelMacroHelper = new ExcelMacroHelper();
            excelMacroHelper.RunExcelMacro(fileDowFullName, macroName, parameters, out objRtn, isShowExcel);
            return objRtn;
        }
    }

}


 

 

using System;
using System.Collections.Generic;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using System.IO;

namespace Sys.LXZX.Core.Utils
{
    /// <summary>
    /// 执行Excel VBA宏帮助类
    /// </summary>
    public class ExcelMacroHelper
    {
        /// <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 RunExcelMacro(
                                            string excelFilePath,
                                            string macroName,
                                            object[] parameters,
                                            out object rtnValue,
                                            bool isShowExcel
                                        )
        {
            try
            {
                #region 检查入参

                // 检查文件是否存在
                if (!File.Exists(excelFilePath))
                {
                    throw new System.Exception(excelFilePath + " 文件不存在");
                }

                // 检查是否输入宏名称
                if (string.IsNullOrEmpty(macroName))
                {
                    throw new System.Exception("请输入宏的名称");
                }

                #endregion

                #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对象示例
                Excel.ApplicationClass oExcel = new Excel.ApplicationClass();

                // 判断是否要求执行时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

                #region 释放对象

                // 释放Workbook对象
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
                oBook = null;

                // 释放Workbooks对象
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks);
                oBooks = null;

                // 关闭Excel
                oExcel.Quit();

                // 释放Excel对象
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
                oExcel = null;

                // 调用垃圾回收
                GC.Collect();

                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <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;
                }
            }
        }
    }

}


 

 

 

调用方法

 

         DataTable dt = DBHelper.GetDataTable("select  top 20 * from 任务_出勤");
           string downloadName = System.DateTime.Now.ToString("yyyyMMddHHssmm");
           ExcelDownHelper edownHelper = new ExcelDownHelper(@"E:\\", "test.xls", "test" + downloadName + ".xls");
           edownHelper.TableToExcel(dt,"",true,1);
         //  edownHelper.RunExcelMacro("hongse",null,false);
           edownHelper.fileDownLoad(true);
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值