上一篇,介紹了怎麼導出Excel文件,這篇文章介紹在ASP.NET MVC中使用水晶報表。
項目源碼下載:https://github.com/caofangsheng93/CrystalReportInMac
前提條件:你需要有VS,SQL Server 當然最重要的就是安裝Crystal Report。
這裡我提供我百度網盤的安裝文件:http://pan.baidu.com/s/1bpcK3ZD,我這裡是Crystal Report for VS2013的版本。需要其他的版本大家自己去搜去下載。
環境搭配好之後,就開始干,我們先創建數據庫:
USE master GO IF EXISTS(SELECT * FROM sysdatabases WHERE name='CustomerDB') DROP DATABASE CustomerDB GO CREATE DATABASE CustomerDB GO USE CustomerDB GO IF EXISTS(SELECT * FROM sysobjects WHERE name='Customers') DROP TABLE Customers GO CREATE TABLE Customers ( CustomerID INT NOT NULL PRIMARY KEY IDENTITY(1,1), CustomerName NVARCHAR(50) NULL, CustomerEmail NVARCHAR(50) NULL, CustomerZipCode INT NULL, CustomerCountry NVARCHAR(50) NULL, CustomerCity NVARCHAR(50) NULL ) --插入測試數據 INSERT INTO dbo.Customers SELECT N'李易峰','李易峰@163.com','436500',N'中國',N'深圳' UNION ALL SELECT N'孫尚香','孫尚香@163.com','436501',N'中國',N'上海' UNION ALL SELECT N'蘭陵王','蘭陵王@163.com','436502',N'中國',N'北京' UNION ALL SELECT N'孫悟空','孫悟空@163.com','436503',N'中國',N'武漢' UNION ALL SELECT N'曹操','曹操@163.com','436504',N'中國',N'杭州'
然後,我們的項目是這樣的:
弄好數據庫之後,我們新建一個ADO.NET實體數據模型:命名隨便,我這裡命名:DbContextCustomer
接著就是新建一個水晶報表了:
Next, window will pop up as given below, in this example we are going to choose "As a Blank Report" option, and click OK.
After clicking OK, our Crystal Report has been created with success. The next step is to right click on Database Fields > Database Expert…
Now, a new window will pop up as shown below. We need to select model which will be using to display data (in this case our model is Customer). After clicking OK, we proceed to drag all fields to the report as shown below.
然後就是創建控制器:
public class CustomerController : Controller { private CustomerDBEntities context = new CustomerDBEntities(); public ActionResult Index() { var customerList= context.Customers.ToList(); return View(customerList); } public ActionResult ExportCustomers() { List<Customer> allCustomer = new List<Customer>(); allCustomer = context.Customers.ToList(); ReportDocument rd = new ReportDocument(); rd.Load(Path.Combine(Server.MapPath("~/CrystalReports"), "ReportCustomer.rpt")); rd.SetDataSource(ToDataTable<Customer>(allCustomer)); Response.Buffer = false; Response.ClearContent(); Response.ClearHeaders(); Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); stream.Seek(0, SeekOrigin.Begin); return File(stream, "application/pdf", "CustomerList.pdf"); } /// <summary> /// 將泛型集合類轉換成DataTable /// </summary> /// <typeparam name="T">集合項類型</typeparam> /// <param name="list">集合</param> /// <param name="propertyName">需要返回的列的列名</param> /// <returns>數據集(表)</returns> public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName) { List<string> propertyNameList = new List<string>(); if (propertyName != null) propertyNameList.AddRange(propertyName); DataTable result = new DataTable(); if (list.Count > 0) { PropertyInfo[] propertys = list[0].GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { if (propertyNameList.Count == 0) { result.Columns.Add(pi.Name, pi.PropertyType); } else { if (propertyNameList.Contains(pi.Name)) result.Columns.Add(pi.Name, pi.PropertyType); } } for (int i = 0; i < list.Count; i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in propertys) { if (propertyNameList.Count == 0) { object obj = pi.GetValue(list[i], null); tempList.Add(obj); } else { if (propertyNameList.Contains(pi.Name)) { object obj = pi.GetValue(list[i], null); tempList.Add(obj); } } } object[] array = tempList.ToArray(); result.LoadDataRow(array, true); } } return result; } }
視圖代碼:
@model IEnumerable<CryStalReportInMvc.Customer> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") <div><a href="@Url.Action("ExportCustomers")">Report PDF</a></div> </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.CustomerName) </th> <th> @Html.DisplayNameFor(model => model.CustomerEmail) </th> <th> @Html.DisplayNameFor(model => model.CustomerZipCode) </th> <th> @Html.DisplayNameFor(model => model.CustomerCountry) </th> <th> @Html.DisplayNameFor(model => model.CustomerCity) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.CustomerName) </td> <td> @Html.DisplayFor(modelItem => item.CustomerEmail) </td> <td> @Html.DisplayFor(modelItem => item.CustomerZipCode) </td> <td> @Html.DisplayFor(modelItem => item.CustomerCountry) </td> <td> @Html.DisplayFor(modelItem => item.CustomerCity) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) | @Html.ActionLink("Details", "Details", new { id=item.CustomerID }) | @Html.ActionLink("Delete", "Delete", new { id=item.CustomerID }) </td> </tr> } </table> View Code
效果圖:
點擊Report PDF之後:
這樣就實現了報表的功能。