• <menu id="w2i4a"></menu>
  • logo Fastreport.Net 教程2018(完結(jié))

    文檔首頁>>Fastreport.Net 教程2018(完結(jié))>>如何使用Ajax從FastReport Web API獲取報表

    如何使用Ajax從FastReport Web API獲取報表


    在文章“如何在ASP.NET Web API中使用FastReport.Net”中,我們已經(jīng)討論了如何創(chuàng)建一個用于生成報表的Web服務(wù)。然后我們會收到報表的鏈接,現(xiàn)在我們來看看如何獲??取報表并使用ajax腳本顯示它。

    讓我提醒你一下,我們的服務(wù)可以返回以這些格式之一導(dǎo)出的報表:PDF、HTML、PNG。我們將以HTML格式接收報表,并使用ajax腳本將其顯示在網(wǎng)頁上。

    我們接下來講解一下從頭開始創(chuàng)建WebApi應(yīng)用程序的過程。首先,創(chuàng)建一個ASP.Net應(yīng)用程序,WebAPI。選擇空模板并勾選選項:MVC和WebApi。

    如何使用Ajax從FastReport Web API獲取報表

    在項目引用中,添加FastReport.dll庫。

    我們繼續(xù)創(chuàng)建一個數(shù)據(jù)模型?,F(xiàn)在Model文件夾是空的。點擊右鍵并選擇“Add”,“Class”。

    將其命名為Reports.cs。添加兩個字段:Id和ReportName:

    namespace FastReportWebApiDemo.Models
    {
     public class Reports
     {
     // Report ID
     public int Id { get; set; }
     // Report File Name
     public string ReportName { get; set; }
     }
    }
    

    你需要將報表模板和數(shù)據(jù)庫文件放在App_Data文件夾中。在我們的例子中,我們把這兩個報表放進(jìn)去:“Simple List.frx”和“Barcode.frx”;

    現(xiàn)在,在Controllers文件夾中,添加控制器ReportsController。它將包含應(yīng)用程序的所有邏輯。我們使用Controllers文件夾的上下文菜單執(zhí)行此操作。選擇“添加” - >“控制器“:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using FastReport;
    using FastReport.Export.Image;
    using FastReport.Export.Html;
    using FastReport.Export.Pdf;
    using FastReport.Utils;
    using FastReportWebApiDemo.Models;
    using System.Web.Hosting;
    using System.Data;
    using System.IO;
    using System.Net.Http.Headers;
     
    namespace FastReportWebApiDemo.Controllers
    {
    // Transfer class with parameters for requesting a report
     public class ReportQuery
     {
     // Format of resulting report: png, pdf, html
     public string Format { get; set; }
     // Value of "Parameter" variable in report
     public string Parameter { get; set; }
     // Enable Inline preview in browser (generates "inline" or "attachment")
     public bool Inline { get; set; }
     }
     
     public class ReportsController : ApiController
     { //Reports list
     Reports[] reportItems = new Reports[]
     {
     new Reports { Id = 1, ReportName = "Simple List.frx" },
     new Reports { Id = 2, ReportName = "Barcode.frx" }
     };
     
     // Get list of reports
     public IEnumerable<Reports> GetAllReports()
     {
     return reportItems;
     }
     
     // Get report by ID from request
     public HttpResponseMessage GetReportById(int id, [FromUri] ReportQuery query)
     {
     // Find report
     Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id);
     if (reportItem != null)
     {
     string reportPath = HostingEnvironment.MapPath("~/App_Data/" + reportItem.ReportName);
     string dataPath = HostingEnvironment.MapPath("~/App_Data/nwind-employees.xml");
     MemoryStream stream = new MemoryStream();
     try
     {
     using (DataSet dataSet = new DataSet())
     {
    // Fill the data source with the data
     dataSet.ReadXml(dataPath);
    // Enable FastReport web mode
     Config.WebMode = true;
     using (Report report = new Report())
     {
     report.Load(reportPath); // Load the report
     report.RegisterData(dataSet, "NorthWind"); // Register the data in the report
     if (query.Parameter != null)
     {
     report.SetParameterValue("Parameter", query.Parameter); // Set the value of the parameter in the report. The very meaning we take from the URL
     }
     
     // Two phases of preparation to exclude the display of any dialogs
     report.PreparePhase1();
     report.PreparePhase2();
     
     if (query.Format == "pdf")
     {
    // Export the report to PDF
     PDFExport pdf = new PDFExport();
    // We use the stream to store the report so that we do not produce files
     report.Export(pdf, stream);
     }
     else if (query.Format == "html")
     {
    // Export the report to HTML
     HTMLExport html = new HTMLExport();
     html.SinglePage = true;
     html.Navigator = false;
     html.EmbedPictures = true;
     report.Export(html, stream);
     }
     else if (query.Format == "png")
     {
    // Export the report to PNG
     using (ImageExport img = new ImageExport())
     {
     img.ImageFormat = ImageExportFormat.Png;
     img.SeparateFiles = false;
     img.ResolutionX = 96;
     img.ResolutionY = 96;
     report.Export(img, stream);
     query.Format = "png";
     }
     }
     else
     {
     WebReport webReport = new WebReport();// Create a report object
     webReport.Report.Load(reportPath); // Load the report
     webReport.Report.RegisterData(dataSet, "NorthWind"); // Register the data source in the report
     if (query.Parameter != null)
     {
     webReport.Report.SetParameterValue("Parameter", query.Parameter); // Set the value of the report parameter
     }
     // inline registration of FastReport javascript
     webReport.InlineRegistration = true; // Allows you to register scripts and styles in the body of the html-page instead of placing them in the title
     webReport.Width = Unit.Percentage(100);
     webReport.Height = Unit.Percentage(100);
     // get control
     HtmlString reportHtml = webReport.GetHtml(); // load the report into HTML
     byte[] streamArray = Encoding.UTF8.GetBytes(reportHtml.ToString());
     stream.Write(streamArray, 0, streamArray.Length); // Write the report to the stream
     } 
    }
     }
    // create the resulting variable
     HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
     {
     Content = new ByteArrayContent(stream.ToArray())
     };
     
     stream.Dispose();
     
     result.Content.Headers.ContentDisposition =
     new System.Net.Http.Headers.ContentDispositionHeaderValue(query.Inline ? "inline" : "attachment")
     {
    // Set the file extension depending on the type of export
     FileName = String.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", query.Format)
     };
    // Define the content type for the browser
    result.Content.Headers.ContentType =
     new MediaTypeHeaderValue("application/" + query.Format);
     return result;
     }
    // Handle Exceptions
     catch
     {
     return new HttpResponseMessage(HttpStatusCode.InternalServerError);
     }
     }
     else
     return new HttpResponseMessage(HttpStatusCode.NotFound);
     }
     }
    }
    

    在ReportsController類中,我們創(chuàng)建了一個報表數(shù)組和兩個方法。名稱和報表標(biāo)識符在數(shù)組中定義。GetAllReports () 方法返回可用報表的列表。第二種方法 GetReportById (int id, [FromUri] ReportQuery query) 通過標(biāo)識符返回一個報表。從查詢屬性中,我們可以得到參數(shù)格式、內(nèi)聯(lián)和參數(shù)。這三者分別決定:報表的導(dǎo)出格式,報表是否會直接在瀏覽器中打開,傳遞給報表的參數(shù)的值。特別有趣的是 webReport.GetHtml () 方法,它可以讓你獲得報表的HTML視圖。這就是我們使用ajax在頁面上顯示的內(nèi)容。

    在Web.config文件中,你需要添加兩個處理句柄:

    <handlers>
    … 
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
     <add name="FastReportHandler" path="FastReport.Export.axd" verb="*" type="FastReport.Web.Handlers.WebExport" />
    …
    </handlers>
    

    現(xiàn)在添加網(wǎng)頁。在項目上點擊右鍵并選擇Add-> HTML Page。

    一般我們習(xí)慣將起始頁命名為Index。將以下代碼添加到頁面中:

    <!DOCTYPE html>
    <html>
    <head>
     <title></title>
     <meta charset="utf-8" />
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    </head>
    <body>
     <script type="text/javascript" language="javascript">
     function call() {
     var msg = $('#formx').serialize();
     $.ajax({ 
     type: 'GET',// Type
     url: 'http://localhost:58005/api/reports/1', // We receive a file from Rest service
     cache: false,// Caching
     timeout: 30000,// Timeout
     data: msg,
     success: function (data) {// The function will work if the data is successfully received
     $('#results').html(data);// We display the data in the form },
     beforeSend: function (data) {// The function is activated during the waiting period of data
     $('#results').html('<p> Waiting for data...</p>');
     },
     dataType: "html", // Data type 
     error: function (data) {// Function will work if an error occurs
     $('#results').html('<p> Failed to load report</p>');
     }
     });
     }
     </script>
    <form method="GET" id="formx" action="javascript:void(null);" onsubmit="call()">
     <input value="Загрузить" type="submit">
     </form>
     <div id="results" typeof="submit"></div><!-- Here the result will be displayed-->
    </body>
    </html>
    

    從代碼中可以看到,我們只是通過從服務(wù)鏈接請求來加載HTML報表文件。

    從文件夾App_Start打開文件WebApiConfig.cs。為Index頁面添加一個MapHttpRoute:

    public static void Register(HttpConfiguration config)
     {
     // Web API configuration and services
     // Web API routes
     config.MapHttpAttributeRoutes();
     config.Routes.MapHttpRoute(
     name: "Index",
     routeTemplate: "{id}.html",
     defaults: new { id = "index" }
     );
     
     config.Routes.MapHttpRoute(
     name: "DefaultApi",
     routeTemplate: "api/{controller}/{id}",
     defaults: new { id = RouteParameter.Optional }
     );
     }
    

    在同一個文件夾中,找到RouteConfig.cs文件。它可以被刪除。

    打開文件Global.asax。刪除該行: 

    RouteConfig.RegisterRoutes(RouteTable.Routes); 

    現(xiàn)在路由只能通過WebApiConfig來完成。

    運行該應(yīng)用程序,然后單擊“下載”按鈕:

    如何使用Ajax從FastReport Web API獲取報表

    就這樣,我們收到了報表。

    從上面的例子可以清楚的看出,使用Ajax進(jìn)行報表處理是非常簡單的。

    產(chǎn)品介紹 下載試用 | 優(yōu)惠活動 | 在線客服 | 聯(lián)系Elyn

     

    推薦閱讀

    FastReport 2018 最新版本下載
    掃碼咨詢


    添加微信 立即咨詢

    電話咨詢

    客服熱線
    023-68661681

    TOP
    三级成人熟女影院,欧美午夜成人精品视频,亚洲国产成人乱色在线观看,色中色成人论坛 (function(){ var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })();