上一篇,介绍了怎么导出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(,),
CustomerName NVARCHAR() NULL,
CustomerEmail NVARCHAR() NULL,
CustomerZipCode INT NULL,
CustomerCountry NVARCHAR() NULL,
CustomerCity NVARCHAR() NULL
) --插入测试数据
INSERT INTO dbo.Customers
SELECT N'李易峰','李易峰@163.com','',N'中国',N'深圳'
UNION ALL
SELECT N'孙尚香','孙尚香@163.com','',N'中国',N'上海'
UNION ALL
SELECT N'兰陵王','兰陵王@163.com','',N'中国',N'北京'
UNION ALL
SELECT N'孙悟空','孙悟空@163.com','',N'中国',N'武汉'
UNION ALL
SELECT N'曹操','曹操@163.com','',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(, 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 > )
{
PropertyInfo[] propertys = list[].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == )
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
else
{
if (propertyNameList.Contains(pi.Name))
result.Columns.Add(pi.Name, pi.PropertyType);
}
} for (int i = ; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == )
{
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>

效果图:

点击Report PDF之后:

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

2.ASP.NET MVC 中使用Crystal Report水晶报表的更多相关文章

  1. [转]解决crystal report水晶报表在浏览器提示bobj未定义的错误

    网上的中文文章(比如这篇文章)都是写的部署到服务器后出现的问题,同时也指出要把crystal report的aspnet_client文件夹拷贝到对应项目的根目录里,这样就可以正常显示了,但是具体到我 ...

  2. 解决crystal report水晶报表在浏览器提示bobj未定义的错误

    网上的中文文章(比如这篇文章)都是写的部署到服务器后出现的问题,同时也指出要把crystal report的aspnet_client文件夹拷贝到对应项目的根目录里,这样就可以正常显示了,但是具体到我 ...

  3. C# WinForm开发系列 - Crystal Report水晶报表

    转自:ttp://www.cnblogs.com/peterzb/archive/2009/07/11/1521325.html 水晶报表(Crystal Report)是业内最专业.功能最强的报表系 ...

  4. Crystal Report - 水晶报表导出文件的格式设置

    水晶报表中自带的导出和打印功能用起来确实很方便,只不过有时候需要导出的文件并不需要那么多种类型,在网上找到一些朋友的代码总结了一下,可以通过代码实现自定义导出文件类型 首先需要定义一个枚举: publ ...

  5. Crystal Report水晶报表碰到的一些纠结问题

    1.插入PNG文件时,透明的背景会变成黑色.试了矢量图WMF文件,是可以正常显示的,不过毕竟得到矢量图比较困难.   后来找到个方法,就是把JPG图片放在子报表里,调整子报表在父报表的位置并且保持JP ...

  6. 在asp.net mvc中如何使用Grid++ Report (锐浪报表)

    在asp.net mvc中如何使用Grid++ Report (锐浪报表) 在cshtml,razor中的处理方法 以官方的asp.net(csharp)中的第一个示例"1a.简单表格&qu ...

  7. 在ASP.NET MVC 中使用ActiveReports报表控件

    随着MVC模式的广泛运用,对Web应用系统的开发带来了巨大的影响,我们好像又回到了原来的ASP时代,视乎这是一种后退而不是一种进步,不过MVC模式给我们带来的影响不仅限于我们所看到的这一点..MVC看 ...

  8. 关于 ASP.NET MVC 中的视图生成

    在 ASP.NET MVC 中,我们将前端的呈现划分为三个独立的部分来实现,Controller 用来控制用户的操作,View 用来控制呈现的内容,Model 用来表示处理的数据. 从控制器到视图 通 ...

  9. 在Asp.Net MVC 中配置 Serilog

    Serilog 是一种非常简便记录log 的处理方式,使用Serilog可以生成本地的text文件, 也可以通过 Seq 来在Web界面中查看具体的log内容. 接下来就简单的介绍一下在Asp.Net ...

随机推荐

  1. AES加密

    package com.edu.hpu; import java.math.BigInteger; import java.security.MessageDigest; import java.se ...

  2. dubbox微服务实例及引发的“血案”

    Dubbo 是阿里巴巴公司开源的一个高性能优秀的服务框架,使得应用可通过高性能的 RPC 实现服务的输出和输入功能,可以和 Spring框架无缝集成. 主要核心部件: Remoting: 网络通信框架 ...

  3. JavaScript模仿块级作用域

    avaScript 没有块级作用域的概念.这意味着在块语句中定义的变量,实际上是在包含函数中而非语句中创建的,来看下面的例子: function outputNumbers(count){ for ( ...

  4. 玩转spring boot——结合JPA事务

    接着上篇 一.准备工作 修改pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

  5. DOM的小练习,两个表格之间数据的移动

    本次讲的是两个表格之间数据的移动,左边的表格移动到右边,并且左边表格移动内容消失. <head>   <meta http-equiv="Content-Type" ...

  6. Android之DOM解析XML

    一.DOM解析方法介绍 DOM是基于树形结构的节点或信息片段的集合,允许开发人员使用DOM API遍历XML树,检索所需数据.分析该结构通常需要加载整个文档和构造树形结构,然后才可以检索和更新节点信息 ...

  7. NV显卡Ubuntu14.04更新软件导致登录死循环,不过可以进入tty模式

    注意:此方法只适用于nv显卡的电脑! 在网上寻找各种方法无果的情况下,选择重新安装显卡驱动,成功登录进入图形界面. 一.首先需要在另外一台电脑(windows系统也可以)上下载NVIDIA相应显卡驱动 ...

  8. BZOJ 1692: [Usaco2007 Dec]队列变换 [后缀数组 贪心]

    1692: [Usaco2007 Dec]队列变换 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 1383  Solved: 582[Submit][St ...

  9. Javascript高级技巧

    上次整理了Ajax部分,这周看完了高级技巧部分,也整理下吧. 1.类型检测 使用Object.prototype.toString.call(obj)的方式. 因为无论typeof还是instance ...

  10. AngularJs2与AMD加载器(dojo requirejs)集成

    现在是西太平洋时间凌晨,这个问题我鼓捣了一天,都没时间学英语了,英语太差,相信第二天我也看不懂了,直接看结果就行. 核心原理就是require在AngularJs2编译过程中是关键字,而在浏览器里面运 ...