C#执行Excel宏模版的方法(3)

//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进程容易死掉,导致资源无法释放,因此需要使用这个方法来释放死掉的进程

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wydpyy.html