如何使用FastReport Core以PDF格式下载报表
本文将展示如何创建一个按钮,实现一键将报表从浏览器下载到本地。我们将在最终文件的功能中使用导出为PDF(当然你可以使用任何其他格式)。
首先,创建一个ASP.NET Core Web Application项目并添加下列库:FastReport Core、Microsoft.EntitiyFrameworkCore.Sqlite以及Microsoft.EntitiyFrameworkCore.Sqlite.Design。这样,你就有了已安装好的以下软件包:
让我们预先处理数据。我们需要SQLite数据库 - fastreport.db。可以从示范项目“C:\ Program Files (x86)\FastReports\FastReport.Net\Demos\Core\FastReportCore.MVC” 中获取。将数据库直接添加到项目的根目录。另外,我们从项目文件夹“C:\Program Files (x86)\FastReports\FastReport.Net\Demos\Reports”中添加报告模板“Simple List.frx”。
现在,在Models文件夹中,添加一个新的类。我们称之为ApplicationDbContext.cs。从名字你大概就能看出来了 - 这是数据的上下文。这是它的内容:
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 //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; } } }
在这个类中(在连接到数据库后)我们得到一组数据并将其转换为一个DataTable,这是FastReport生成报表所需的。将在报表中使用的Employees表的模型由一个单独的类表示。
现在我们开始编辑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格式显示报表,而PDF方法则生成一个用于下载的PDF文件。这两种方法都使用报表的数据上下文。
现在改变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"]) }
我们首先添加了一个PDF下载按钮,然后显示报表。
运行应用程序:
我们按下“下载PDF”按钮,并以PDF格式下载报表文件。总而言之,实现起来相当简单。
推荐阅读
- FastReport VCL报表控件开发者手册
- FastReport Online Designer中文手册
- Fastreport.Net教程2016
- Fastreport.Net用户手册
- FastReport.Net教程2017(持续更新中···)
- FastReport Online Designer教程2017(持续更新中···)
- 报表教程2017(持续更新中···)
- FastReport.Net v2018.1版本更新已经发布!