如何使用FastReport Core以PDF格式下載報(bào)表
本文將展示如何創(chuàng)建一個(gè)按鈕,實(shí)現(xiàn)一鍵將報(bào)表從瀏覽器下載到本地。我們將在最終文件的功能中使用導(dǎo)出為PDF(當(dāng)然你可以使用任何其他格式)。
首先,創(chuàng)建一個(gè)ASP.NET Core Web Application項(xiàng)目并添加下列庫:FastReport Core、Microsoft.EntitiyFrameworkCore.Sqlite以及Microsoft.EntitiyFrameworkCore.Sqlite.Design。這樣,你就有了已安裝好的以下軟件包:
讓我們預(yù)先處理數(shù)據(jù)。我們需要SQLite數(shù)據(jù)庫 - fastreport.db??梢詮氖痉俄?xiàng)目“C:\ Program Files (x86)\FastReports\FastReport.Net\Demos\Core\FastReportCore.MVC” 中獲取。將數(shù)據(jù)庫直接添加到項(xiàng)目的根目錄。另外,我們從項(xiàng)目文件夾“C:\Program Files (x86)\FastReports\FastReport.Net\Demos\Reports”中添加報(bào)告模板“Simple List.frx”。
現(xiàn)在,在Models文件夾中,添加一個(gè)新的類。我們稱之為ApplicationDbContext.cs。從名字你大概就能看出來了 - 這是數(shù)據(jù)的上下文。這是它的內(nèi)容:
using Microsoft.EntityFrameworkCore; using System; using System.Data; using System.Reflection; namespace FRCore { public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public ApplicationDbContext() { } public DbSet<Employees> Employees { get; set; } // Get the data set public DataSet GetDataSet(string name) { DataSet set = new DataSet(name); set.Tables.Add(GetTable(Employees, "Employees")); return set; } // Set the primary key protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Employees>(entity => { entity.HasKey(e => e.EmployeeId) .HasName("sqlite_autoindex_employees_1"); }); } // Set the data source protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. optionsBuilder.UseSqlite(@"data source= fastreport.db"); } // Get the table you need to create a report. In fact, the method of converting IQuerable into a DataTable static DataTable GetTable<TEntity>(DbSet<TEntity> table, string name) where TEntity : class { DataTable result = new DataTable(name); PropertyInfo[] infos = typeof(TEntity).GetProperties(); foreach (PropertyInfo info in infos) { if (info.PropertyType.IsGenericType && info.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) result.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType))); else result.Columns.Add(new DataColumn(info.Name, info.PropertyType)); } foreach (var el in table) { DataRow row = result.NewRow(); foreach (PropertyInfo info in infos) if (info.PropertyType.IsGenericType && info.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { object t = info.GetValue(el); if (t == null) t = Activator.CreateInstance(Nullable.GetUnderlyingType(info.PropertyType)); row[info.Name] = t; } else row[info.Name] = info.GetValue(el); result.Rows.Add(row); } return result; } } // The Employees table model public class Employees { public int EmployeeID { get; set; } public int EmployeeId { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public string Title { get; set; } public string TitleOfCourtesy { get; set; } public System.DateTime? BirthDate { get; set; } public System.DateTime? HireDate { get; set; } public string Address { get; set; } public string City { get; set; } public string Region { get; set; } public string PostalCode { get; set; } public string Country { get; set; } public string HomePhone { get; set; } public string Extension { get; set; } public byte[] Photo { get; set; } public string Notes { get; set; } public int? ReportsTo { get; set; } } }
在這個(gè)類中(在連接到數(shù)據(jù)庫后)我們得到一組數(shù)據(jù)并將其轉(zhuǎn)換為一個(gè)DataTable,這是FastReport生成報(bào)表所需的。將在報(bào)表中使用的Employees表的模型由一個(gè)單獨(dú)的類表示。
現(xiàn)在我們開始編輯HomeController.cs。
using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using FRCore.Models; using FastReport; using FastReport.Export.Html; using System.IO; using System.Text; using FastReport.Export.Pdf; using System.Data; namespace FRCore.Controllers { public class HomeController : Controller { public Report report = new Report(); private ApplicationDbContext _context = new ApplicationDbContext(); public ApplicationDbContext GetContext() { return _context; } public IActionResult Index() { DataSet dataSet = new DataSet(); dataSet = GetContext().GetDataSet("NorthWind"); report.Report.RegisterData(dataSet, "NorthWind"); report.Report.Load("Simple List.frx"); report.Prepare(); HTMLExport export = new HTMLExport(); export.Layers = true; using (MemoryStream ms = new MemoryStream()) { export.EmbedPictures = true; export.Export(report, ms); ms.Flush(); ViewData["Report"] = Encoding.UTF8.GetString(ms.ToArray()); ViewData["ReportName"] = "Simple List.frx"; } return View(); } public IActionResult Pdf() { System.Data.DataSet dataSet = new System.Data.DataSet(); dataSet = GetContext().GetDataSet("NorthWind"); report.Report.RegisterData(dataSet, "NorthWind"); report.Report.Load("Simple List.frx"); report.Prepare(); PDFExport export = new PDFExport(); using (MemoryStream ms = new MemoryStream()) { export.Export(report, ms); ms.Flush(); return File(ms.ToArray(), "application/pdf", Path.GetFileNameWithoutExtension("Simple List") + ".pdf"); } } } }
Index方法只是以html格式顯示報(bào)表,而PDF方法則生成一個(gè)用于下載的PDF文件。這兩種方法都使用報(bào)表的數(shù)據(jù)上下文。
現(xiàn)在改變Index.cshtml的顯示形式:
@{ ViewData["Title"] = "Home Page"; } @if (ViewData.ContainsKey("ReportName")) { <a class="btn btn-danger" asp-controller="Home" asp-action="Pdf" asp-route-report="@ViewData["ReportName"]">Download PDF</a> } @if (ViewData.ContainsKey("Report")) { @Html.Raw(ViewData["Report"]) }
我們首先添加了一個(gè)PDF下載按鈕,然后顯示報(bào)表。
運(yùn)行應(yīng)用程序:
我們按下“下載PDF”按鈕,并以PDF格式下載報(bào)表文件。總而言之,實(shí)現(xiàn)起來相當(dāng)簡(jiǎn)單。
產(chǎn)品介紹 | 下載試用 | 優(yōu)惠活動(dòng) | 在線客服 | 聯(lián)系Elyn
推薦閱讀
- FastReport VCL報(bào)表控件開發(fā)者手冊(cè)
- FastReport Online Designer中文手冊(cè)
- Fastreport.Net教程2016
- Fastreport.Net用戶手冊(cè)
- FastReport.Net教程2017(持續(xù)更新中···)
- FastReport Online Designer教程2017(持續(xù)更新中···)
- 報(bào)表教程2017(持續(xù)更新中···)
- FastReport.Net v2018.1版本更新已經(jīng)發(fā)布!