想要在.aspx文件中使用水晶报表
1.先新建文件webform1.aspx 在页面拖入组件CrystalReportViewer 生成代码

2.在项目的同个文件夹中新建文件crystalreport1.rpt? 在字段资源管理器的数据库字段“添加数据库” 请使用oledb连接 从而选择你所要在报表中显示的数据表(有向导)

3.在webform1.aspx.cs主要代码如下:
protected CrystalDecisions.Web.CrystalReportViewer CrystalReportViewer1;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
TableLogOnInfo logOnInfo = new TableLogOnInfo ();
ReportDocument oRpt = new ReportDocument();
string RptDir="f:\\bbs\\test\\crystal\\crystalreport1.rpt"; //crystalreport1.rpt文件所在的绝对路径
oRpt.Load(RptDir);

//设置logOnInfo参数,注意这里如果不设?编译时最容易出现“登陆失败”的错误!
logOnInfo.ConnectionInfo.ServerName = "服务器名";
logOnInfo.ConnectionInfo.DatabaseName = "数据库名";
logOnInfo.ConnectionInfo.UserID = "用户名";
logOnInfo.ConnectionInfo.Password = "密码";
oRpt.Database.Tables [0].ApplyLogOnInfo(logOnInfo);

//建立.rpt文件与CryStalReportviewer文件之间的连接
CrystalReportViewer1.ReportSource=oRpt;
}

4.//生成pdf文档 在以上代码中加入
 ExportOptions crExportOptions=new ExportOptions();
DiskFileDestinationOptions crDiskFileDestinationOptions=new DiskFileDestinationOptions();
crDiskFileDestinationOptions.DiskFileName="f:\\bbs\\test\\crystal\\crystalreport1.pdf";
crExportOptions=oRpt.ExportOptions ;
crExportOptions.DestinationOptions=crDiskFileDestinationOptions;
crExportOptions.ExportDestinationType =ExportDestinationType.DiskFile;
crExportOptions.ExportFormatType =ExportFormatType.PortableDocFormat ;

oRpt.Export();
oRpt.Close();

5.//读取报表导出的内容并传到客户端?继续加入以下代码
Response.ClearContent();
Response.ClearHeaders ();
Response.ContentType ="application/pdf";
Response.WriteFile("f:\\bbs\\test\\crystal\\crystalreport1.pdf");

Response.Flush();
Response.Close();?

2005年9月30日 16:21

引自:http://dotnet.mblogger.cn/workhyj/posts/5823.aspx