65.9K
CodeProject 正在变化。 阅读更多。
Home

如何使用 C# 导出 Crystal Report

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.38/5 (16投票s)

2007 年 3 月 9 日

3分钟阅读

viewsIcon

132262

本文介绍了如何使用 C# 自定义导出 Crystal Report。

引言

我一直在寻找一些好的代码,它允许程序员以编程方式导出 Crystal Report,而无需使用 Crystal Reports 附带的(并非总是)功能按钮。这是一篇关于如何以最常见的格式导出 Crystal Report 的简短、直接的文章。代码是 C#,在 ASP.NET 后台代码文件中。

我使用通过下拉列表导出,我已预先填充了 4 个值

1 - 富文本格式

2 - PDF

3 - Word (DOC)

4 - Excel

在下拉列表的 SelectedIndexChanged 事件中,我调用该函数来导出报表

注意(要包含的命名空间)

请记住包含正确的命名空间,包括内存引用和加载和运行 Crystal Report 所需的命名空间

using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.IO;

代码

protected void ddlExportTypes_SelectedIndexChanged(object sender, EventArgs e)
{

ExportReport();

}

//这是 ExportReport 函数

private void ExportReport()

{

//声明一个 memorystream 对象,它将保存我们的输出
MemoryStream oStream;

//这里是一个有效报表的实例,我们已经 Load(ed) 了它

crReport= new ReportDocument();

/**请记住,在运行此代码之前,必须先加载有效的 crystal report**/

//清除响应并将 Buffer 设置为 true

Response.Clear();

Response.Buffer = true;

switch(ddlExportTypes.SelectedItem.Value)

{

case "1"

// ...富文本 (RTF)

oStream = (MemoryStream)crReport.ExportToStream(CrystalDecisions.Shared.ExportFormatType.RichText);

Response.ContentType = "application/rtf";

break;

case "2"

// ...便携式文档 (PDF)


oStream = (MemoryStream)crReport.ExportToStream(ExportFormatType.PortableDocFormat);

Response.ContentType = "application/pdf";

//如果您想将其导出为附件,请使用以下行

/*

crReport.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "您的导出文件名");

* */


break;

case "3"

// ...MS Word (DOC)

oStream = (MemoryStream)crReport.ExportToStream(ExportFormatType.WordForWindows);

Response.ContentType = "application/doc";

break;

case "4"

// ...MS Excel (XLS)

oStream = (MemoryStream)crReport.ExportToStream(ExportFormatType.Excel);

Response.ContentType = "application/vnd.ms-excel";

break;

默认

//...便携式文档 (PDF)

oStream = (MemoryStream)crReport.ExportToStream(ExportFormatType.PortableDocFormat);

Response.ContentType = "application/pdf";

break;

}


try

{

//将报表写入 Response 流

Response.BinaryWrite(oStream.ToArray());

Response.End();

}

catch (Exception ex)

{

labelErrors.Text = "错误: " + Server.HtmlEncode(ex.Message.ToString());

}

finally

{

//清除流

oStream.Flush();

oStream.Close();

oStream.Dispose();

}

}

注意

报表引擎可以处理一个处理限制。 默认值为 75。这对于许多情况来说可能太低。在这种情况下,您有两个选择

1) 更改 Windows 中的注册表,以允许打印更多报表(小心编辑注册表值,不要过度增加,因为运行报表需要更多内存)

HKEY_LOCAL_MACHINE > SOFTWARE > Crystal Decisions > Report Application Server > InprocServer > 找到 PrintJobLimit 并将值从 75 更改为您想要的值

2) 在您的代码页面中关闭报表(首选方法,但与上述步骤一起执行将使整个报告体验更好)在 Page_Unload 中。 例如

protected void Page_Unload(object sender, EventArgs e)

{

crReport.Close();

}

这将加载报表,打印它并关闭它。 您可以在代码中的其他地方关闭报表,但请小心您关闭它的位置。 从 MS 阅读更多

http://msdn2.microsoft.com/en-us/library/ms225490(VS.80).aspx

© . All rights reserved.