以不同格式导出 Crystal Reports






2.40/5 (15投票s)
一篇关于以不同格式导出 Crystal Reports 的文章。
引言
本文旨在提供一种简单的方法,使用 Crystal Reports .NET 将丰富的报表功能融入到您的应用程序中。 微软提供了一个与 Visual Studio .NET 集成的 Crystal Report 开发环境。 使用此环境开发报表非常容易,并且在 Crystal Reports .Net 中开发的报表可以通过仅仅包含几行代码来轻松导出为 Adobe Acrobat 可移植文档格式或 Micrsoft Word 格式。
背景
本文面向对 Crystal Reports 有基本了解并需要了解如何以用户选择的不同格式导出 Crystal Report 的读者。 该代码是通用代码,可以通过更改下面解释的极少配置设置来使用。
使用代码
在使用此代码之前,请使用 Crystal Report .Net 在 Visual Studio 中通过连接到数据库来创建报表。 这里假设报表是使用拉取方法开发的,即在设计时连接到数据库并绑定报表字段。 源代码提供了 ReportPageBase.cs 类,该类可以在需要显示报表的页面中被继承。 在单击按钮或页面加载时,调用重载函数 LoadReport,该函数至少接受两个参数:报表名称和报表格式作为 ReportExportFormat 枚举。 如果报表需要过滤或报表中的某些参数(例如报表标题的动态显示),则必须使用具有更多参数的相同函数,即 LoadReport
函数。 LoadReport
函数调用 ReportUtility
类的 GenerateReport,该类实际上为提供的参数生成报表。
private void wcbtnGetReport_Click(object sender, System.EventArgs e)
{
try
{
objCrystalReportViewer.Visible= true;
LoadReport(wctbReportName.Text, GetReportFormat(
wclstReportFormat.SelectedItem.Value.ToString()));
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
其中一个值得关注的代码是数据库连接代码。 该代码允许报表通过设置配置文件在运行时连接到数据库。 在配置文件中,根据项目需求更改粗体项目的数值。
<appSettings>
<add key="ReportServerName" value="10.200.32.216"/>
<add key="ReportDataBaseName" value="Northwind"/>
<add key="ReportUserId" value="sa"/>
<add key="ReportPasswd" value=""/>
<add key="PhysicalReportPath" value="C:\\inetpub\\wwwroot\\ReportUI\\"/>
<add key="ReportExportedTempReportPath" value="D:\\Temp\\"/>
</appSettings>
所以您可以看到,它处理了开发和部署环境,如果两者不同(在大多数情况下都是如此)。
LoadReport
函数调用 ReportUtility
类的 GenerateReport
,该函数实际上为提供的参数生成报表。 其中一个值得关注的代码是数据库连接代码。 该代码允许报表在运行时连接到数据库。 所以您可以看到,它处理了开发和部署环境,如果两者不同(在大多数情况下都是如此)。
//Added for configuring the DB connection
foreach(CrystalDecisions.CrystalReports.Engine.Table lrptTable in
lrptDocReportDocument.Database.Tables)
{
lrptTableLogin = lrptTable.LogOnInfo;
lrptTableLogin.ConnectionInfo.ServerName =
ReportConstants.ReportServerName;
lrptTableLogin.ConnectionInfo.DatabaseName =
ReportConstants.ReportDataBaseName;
lrptTableLogin.ConnectionInfo.UserID = ReportConstants.ReportUserId;
lrptTableLogin.ConnectionInfo.Password = ReportConstants.ReportPasswd;
lrptTableLogin.TableName = lrptTable.Name;
lrptTable.ApplyLogOnInfo(lrptTableLogin);
lrptTable.Location = lrptTable.Name;
}