在SQL Server 集成服务中自动获取SharePoint的PowerPivot报表的图表并生成PDF及发送邮件的操作!

      最近做了一个小集成应用测试,适合于对于那些不想在网站上查看相关报表而希望定时通过邮件的方式查看的用户,特别适合相对静态的报表不需要用户进行交互操作),可以使用本文介绍的一种集成操作方法,主要实现思路为:

     1.首先通过SharePoint的ExcelService的Web服务自动获取并下载SharePoint的PowerPivot报表的图表到本机临时文件夹中;

     2.其次通过开源PDF组件的iTextSharp生成本地的图表PDF;

     3.最后通过SSIS中自带的发送邮件任务发送图表PDF到指定邮箱用户中。

      本文以PowerPivotHealthcareAudit.xlsx报表为例,主要获取Dashboard的Sheet中的图表,具体操作步骤如下:

      

     

 

      (一).下载SharePoint的PowerPivotHealthcareAudit.xlsx报表的图表的脚步任务代码,如下:  

/*
   Microsoft SQL Server Integration Services Script Task
   Write scripts using Microsoft Visual C# 2008.
   The ScriptMain is the entry point class of the script.
*/

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace ST_1c6a297d211c4ba690ec8a0a9bd66306.csproj
{
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {

        #region VSTA generated code
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

        /*
        The execution engine calls this method when the task executes.
        To access the object model, use the Dts property. Connections, variables, events,
        and logging features are available as members of the Dts property as shown in the following examples.

        To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
        To post a log entry, call Dts.Log("This is my log text", 999, null);
        To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);

        To use the connections collection use something like the following:
        ConnectionManager cm = Dts.Connections.Add("OLEDB");
        cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";

        Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
        
        To open Help, press F1.
    */

        public void Main()
        {
            // TODO: Add your code here
            ExcelService.ExcelService xlS = new ST_1c6a297d211c4ba690ec8a0a9bd66306.csproj.ExcelService.ExcelService();

            xlS.Url = "http://portal.contoso.uat/sites/cockpit/_vti_bin/ExcelService.asmx";


            //xlS.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            System.Net.NetworkCredential nc = new System.Net.NetworkCredential("UserName", "Password", "contoso.uat");
            xlS.Credentials = nc;


            ExcelService.Status[] status;
            string sessionId = xlS.OpenWorkbook(@"http://portal.contoso.uat/sites/cockpit/PowerPivot/PowerPivotHealthcareAudit.xlsx", string.Empty, string.Empty, out status);

            string url = xlS.GetChartImageUrl(sessionId, null, "Chart 1", out status);

            CreateXlsPng(xlS, url, "Chart 1");

            url = xlS.GetChartImageUrl(sessionId, null, "Chart 2", out status);

            CreateXlsPng(xlS, url, "Chart 2");

            url = xlS.GetChartImageUrl(sessionId, null, "Chart 3", out status);

            CreateXlsPng(xlS, url, "Chart 3");

            url = xlS.GetChartImageUrl(sessionId, null, "Chart 4", out status);

            CreateXlsPng(xlS, url, "Chart 4");

            url = xlS.GetChartImageUrl(sessionId, null, "Chart 13", out status);

            CreateXlsPng(xlS, url, "Chart 13");

            status = xlS.CloseWorkbook(sessionId);

            Dts.TaskResult = (int)ScriptResults.Success;
        }

        private void CreateXlsPng(ExcelService.ExcelService es,string url,string pngname)
        {
            WebRequest req = WebRequest.Create(url);
            req.Credentials = System.Net.CredentialCache.DefaultCredentials;
            using (FileStream output = File.Create("c:\\temp\\" +pngname +".png"))
            using (WebResponse response = req.GetResponse())
            using (Stream input = response.GetResponseStream())
            {
                byte[] buffer = new byte[1024];
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, read);
                }
            }
        }
    }
}

    执行完此脚本后,将在本机c:\temp目前下生成5个图表,具体如下图:

        (二).利用开源PDF组件iTextSharp生成本地的图表PDF的脚步任务代码,如下:  

/*
   Microsoft SQL Server Integration Services Script Task
   Write scripts using Microsoft Visual C# 2008.
   The ScriptMain is the entry point class of the script.
*/

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace ST_8a0e74f918f64cac9fe6e94300fa4ccb.csproj
{
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {

        #region VSTA generated code
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

        /*
        The execution engine calls this method when the task executes.
        To access the object model, use the Dts property. Connections, variables, events,
        and logging features are available as members of the Dts property as shown in the following examples.

        To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
        To post a log entry, call Dts.Log("This is my log text", 999, null);
        To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);

        To use the connections collection use something like the following:
        ConnectionManager cm = Dts.Connections.Add("OLEDB");
        cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";

        Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
        
        To open Help, press F1.
    */

        public void Main()
        {
            // TODO: Add your code here

            ImageDirect();
           
            Dts.TaskResult = (int)ScriptResults.Success;
        }

        public void ImageDirect()
        {
            string imagePath = @"c:\temp\Chart 1.png";
            string fileName = string.Empty;
           
            FileStream fi = System.IO.File.Create(@"c:\temp\PowerPivotHealthcareAudit.pdf");
            fi.Close();

             fileName = @"c:\temp\PowerPivotHealthcareAudit.pdf";
                Document document = new Document();
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
                document.Open();

                iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph("PowerPivotHealthcareAudit", new iTextSharp.text.Font(Font.FontFamily.HELVETICA, 22f));
                p.Alignment = Element.ALIGN_CENTER;
                document.Add(p);

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
                document.Add(img);

                imagePath = @"c:\temp\Chart 2.png";

                iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(imagePath);
                document.Add(img2);

                imagePath = @"c:\temp\Chart 3.png";

                iTextSharp.text.Image img3 = iTextSharp.text.Image.GetInstance(imagePath);
                document.Add(img3);

                imagePath = @"c:\temp\Chart 4.png";

                iTextSharp.text.Image img4 = iTextSharp.text.Image.GetInstance(imagePath);
                document.Add(img4);

                imagePath = @"c:\temp\Chart 13.png";

                iTextSharp.text.Image img5 = iTextSharp.text.Image.GetInstance(imagePath);
                document.Add(img5);

              


                document.Close();
          
        }
    }
}

     执行完此脚本后,将在C:\temp下生成PowerPivotHealthcareAudit.PDF文件,具体如下图:

         (二).在SSIS中添加发送邮件任务,具体如下图: 

   执行完此邮件任务后,用户将收到图表PDF文件,如下图:

 

    通过以上步骤,就实现了一个自动生成图表PDF的集成服务,可以根据需要进一步扩展,以满足实际需求。

 

本博客为软件人生原创,欢迎转载,转载请标明出处:http://www.cnblogs.com/nbpowerboy/archive/2013/05/16/3081599.html 。演绎或用于商业目的,但是必须保留本文的署名软件人生(包含链接)。如您有任何疑问或者授权方面的协商,请给我留言。
posted @ 2013-05-16 19:24  软件人生  阅读(2250)  评论(2编辑  收藏  举报