FastReport中国社区FastReport联系电话 联系电话:023-68661681

如何使用FastReport Core以PDF格式下载报表

来源:   发布时间:2018-01-30   浏览:5127次

本文将展示如何创建一个按钮,实现一键将报表从浏览器下载到本地。我们将在最终文件的功能中使用导出为PDF(当然你可以使用任何其他格式)。

首先,创建一个ASP.NET Core Web Application项目并添加下列库:FastReport Core、Microsoft.EntitiyFrameworkCore.Sqlite以及Microsoft.EntitiyFrameworkCore.Sqlite.Design。这样,你就有了已安装好的以下软件包:

如何使用FastReport Core以PDF格式下载报表

让我们预先处理数据。我们需要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 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; }
 }
}

在这个类中(在连接到数据库后)我们得到一组数据并将其转换为一个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下载按钮,然后显示报表。

运行应用程序:

如何使用FastReport Core以PDF格式下载报表

我们按下“下载PDF”按钮,并以PDF格式下载报表文件。总而言之,实现起来相当简单。


产品介绍 | 下载试用 | 优惠活动 | 在线客服 | 联系Elyn

 

推荐阅读

FastReport 2018 最新版本下载
本站文章除注明转载外,均为本站原创或翻译
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动成果
转载请注明:文章转载自:FastReport控件中文网 [https://www.fastreportcn.com/]
本文地址:https://www.fastreportcn.com/post/2005.html

联系我们
  • 重庆总部 023-68661681
购买
  • sales@evget.com
合作
  • business@evget.com


在线
客服
微信
QQ 电话
023-68661681
返回
顶部