zoukankan      html  css  js  c++  java
  • 2.ASP.NET MVC 中使用Crystal Report水晶报表

    上一篇,介绍了怎么导出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之后:

    这样就实现了报表的功能。

  • 相关阅读:
    Python3输入输出
    Python3文件
    Python3OS文件/方法
    makefile通用版本(一)
    C语言正则表达式
    正则表达式
    sed、awk工具
    shell编程
    Sqlite3-安装使用
    Powershell-获取命令和帮助
  • 原文地址:https://www.cnblogs.com/caofangsheng/p/6150144.html
Copyright © 2011-2022 走看看