博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[置顶] C#执行Excel宏模版的方法
阅读量:4837 次
发布时间:2019-06-11

本文共 6076 字,大约阅读时间需要 20 分钟。

       在项目中如果涉及到用Excel开发的报表模版来导出报表数据的话,一般都是在Excel报表中使用VBA做成宏来进行调用。即先使用Excel自带的VBA开发好报表模版,然后再将模版程序放在固定目录下,在管理软件中对这些报表模版进行调用。这样就不需要使用其它报表工具来进行开发了,因为Excel功能比较强大,一般的应用的报表用它来开发绰绰有余了。而且这样开发的成本也很低,不需要再购买其它专业的报表开发软件直接使用Office开发即可。使用Excel开发的宏模版当然要使用上层程序来调用宏模版了。我以前在工作中就开发过Excel模版,并使用C#程序调用过这些模版程序。规则是首先将报表需要的数据填冲到DataTable或者DataSet中,然后将DataTable或者DataSet中数据导出Excel中。

现提供导出Excel模版的代码如下:

namespace ExcelTest

{
    public class ExelTemplate
    {
        private static Excel.Application ExcelApp;//Define a Excel Application object
        private static Excel._Workbook ExcelWB;//define a Excel workbook object
        private static Excel._Worksheet ExcelWS;//define a Excel workbook worksheet

       //将报表所需的主数据放入dtHeader,明细数据放入dtDetail中,调用的模版名称为strTemplateFileName,导出的报表名称为strOutFileName

        public static bool FillContent(string strTemplateFileName, string strOutFileName, System.Data.DataTable dtHeader, System.Data.DataTable dtDetail)

        {

            bool flag = true;

            FileInfo fileInfo = new FileInfo(strTemplateFileName);

            System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;

            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            try

            {
                //Start Excel and get Application object.               
                ExcelApp = new Excel.Application();
                ExcelApp.Visible  = false;
             
                //Get a new workbook.
                ExcelWB = (Excel._Workbook)(ExcelApp.Workbooks.Add(strTemplateFileName));
               

                //Fill content.注意这里的Header和Detail分别对应模版文件中的Header和Detail两个Sheet页,这2个Sheet是专门用来存放明主数据或者明细数据的。

                if (!FillWorksheet("Header", dtHeader)) return false;
                if (!FillWorksheet("Detail", dtDetail)) return false;

                //Run macro.

               
                ExcelApp.Run("SetData", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
              
                ExcelApp.DisplayAlerts = false;
                //=========================================================================================================
                //Delete Header and Detail.
                //((Excel._Worksheet)ExcelWB.Sheets["Header Information"]).Delete();               
                //((Excel._Worksheet)ExcelWB.Sheets["Detail Information"]).Delete();

 

                //=========================================================================================================
                ExcelApp.DisplayAlerts = true;

                //Delete old file.

                File.Delete(strOutFileName);
                //Save excel file.
                ExcelWB.SaveAs(strOutFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
               
                // Quit Excel.
                ExcelWB.Close(false, strOutFileName, Missing.Value);//*******************             

                MarshalReleaseComObject(ExcelWB);

                ExcelApp.Quit();

               
               
                //Kill excel application.
                //KillProcess("EXCEL");//******************
              
            }
            catch (Exception ex)
            {
                throw ex;  
                flag = false;
            }
            finally
            {
                MarshalReleaseComObject(ExcelApp);
                GC.Collect();
            }

            return flag;

        }

        //将报表所需的主数据放入dtHeader,明细数据放入dtDetail中,调用的模版名称为strTemplateFileName,导出的报表名称为strOutFileName

        public static bool FillContent(string strTemplateFileName, string strOutFileName, System.Data.DataSet dsdata)

        {

            bool flag = true;

            FileInfo fileInfo = new FileInfo(strTemplateFileName);

            System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;

            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            try

            {
                //Start Excel and get Application object.               
                ExcelApp = new Excel.Application();
                ExcelApp.Visible = false;

                //Get a new workbook.

                 ExcelWB = (Excel._Workbook)(ExcelApp.Workbooks.Add(strTemplateFileName));
                 //Fill content.
                //if (!FillWorksheet("Header", dtHeader)) return false;
                //if (!FillWorksheet("Detail", dtDetail)) return false;

                //Fill content.注意这里的没有写明对应模版文件中Sheet页,但是指定了dsdata.Tables[i].TableName为Sheet页的名字,这样方便灵活设置,而且这样可以有多个Sheet是专门用来存放明主数据或者明细数据的。

                for (int i = 0; i < dsdata.Tables.Count; i++)
                {
                    if (!FillWorksheet(dsdata.Tables[i].TableName, dsdata.Tables[i]))
                        return false;
                }

                //Run macro.

             
                ExcelApp.Run("SetData", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
               
                ExcelApp.DisplayAlerts = false;
                //=========================================================================================================
                //Delete Header and Detail.
                //((Excel._Worksheet)ExcelWB.Sheets["Header Information"]).Delete();               
                //((Excel._Worksheet)ExcelWB.Sheets["Detail Information"]).Delete();

 

                //=========================================================================================================
                ExcelApp.DisplayAlerts = true;

                //Delete old file.

                File.Delete(strOutFileName);
                //Save excel file.
               
                ExcelWB.SaveAs(strOutFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
               
                // Quit Excel.
                ExcelWB.Close(false, strOutFileName, Missing.Value);//*******************             

                MarshalReleaseComObject(ExcelWB);

                ExcelApp.Quit();

             

            }

            catch (Exception ex)
            {
                throw ex;
                flag = false;
            }
            finally
            {
                MarshalReleaseComObject(ExcelApp);
                GC.Collect();
            }

            return flag;

        }

        //使用Excel来导出报表时,在服务器上的Excel进程容易死掉,导致资源无法释放,因此需要使用这个方法来释放死掉的进程

        private static void MarshalReleaseComObject(object objCom)

        {
            try
            {
                int i = 1;
                if (objCom != null && System.Runtime.InteropServices.Marshal.IsComObject(objCom))
                {
                    do
                    {
                        i = System.Runtime.InteropServices.Marshal.ReleaseComObject(objCom);
                    } while (i > 0);
                }
            }
            finally
            {
                objCom = null;
            }
        }

}

         

转载于:https://www.cnblogs.com/kevinGao/archive/2011/09/27/2336491.html

你可能感兴趣的文章
ios触摸事件处理
查看>>
apache 整合svn
查看>>
Oracle 测试语句
查看>>
linux计划任务
查看>>
Egg 企业级应用开发框架的搭建
查看>>
input与button按钮背景图失效不显示的解决办法
查看>>
[Mac入门]如何在Mac下显示Finder中的所有文件
查看>>
证明二叉查找树所有节点的平均深度为O(logN)
查看>>
JavaScript基础--简单功能的计算器(十一)
查看>>
WPF Visifire使用 ---- 基础篇二
查看>>
SSAS: Using DMV Queries to get Cube Metadata
查看>>
操作系统存储器管理选择题精练
查看>>
一条咸鱼的养成
查看>>
修复LSP 解决不能上网问题
查看>>
第四周作业总结
查看>>
修改之前某次commit日志和内容
查看>>
动态规划:HDU1712-ACboy needs your help(分组背包问题)
查看>>
PAT A1009 Product of Polynomials(25)
查看>>
libFFM 与 python-libffm 安装遇到的一系列问题-解决方案
查看>>
数据摘要pandas
查看>>