猿问

在MVC中将RDLC的二进制流数据通过RenderAction显示到页面上面

public static class HotelReport
{
public static byte[] GenerateReport(string dtatSetName, IEnumerable dataSource,
                          string reportFilePath,string reportType, out string mimeType, 
                           out string encoding, out string fileNameExtension)
{
//报表数据源
ReportDataSource reportDataSource = new ReportDataSource(dtatSetName, dataSource);
//本地化报表
LocalReport localReport = new LocalReport();
localReport.ReportPath = reportFilePath;
localReport.DataSources.Add(reportDataSource);

string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + reportType + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";

Warning[] warnings;
string[] streams;
byte[] renderedBytes;

renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);

return renderedBytes;
}
}

上面是用于将RDLC报表转换为二进制数据的方法。

下面的ReporesRelsult用于将这种数据写到输出当中

    public class ReportsResult : ActionResult
{
public ReportsResult(byte[] data, string mineType)
{
this.Data = data;
this.MineType = mineType;
}

public byte[] Data { get; set; }
public string MineType { get; set; }

public override void ExecuteResult(ControllerContext context)
{
if (Data == null)
{
new EmptyResult().ExecuteResult(context);
return;
}
context.HttpContext.Response.ContentType = MineType;

using (MemoryStream ms = new MemoryStream(Data))
{
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
context.HttpContext.Response.Output.Write(sr.ReadToEnd());
}
}
}
}

下面是控制器的action方法:

public ActionResult EmployeesNumberPerYear()
{
string dtatSetName = "DsENPerYear";
var dataSource = EmployeeReports.EmployeesNumberPerYear(employeeRepository);
string reportFilePath = Server.MapPath("~/RDLC/Employee/EmployeesNumberPerYear.rdlc");
string reportType = "PDF";

string mimeType;
string encoding;
string fileNameExtension;

byte[] renderedBytes = HotelReport.GenerateReport(dtatSetName, dataSource, reportFilePath,
reportType, out mimeType, out encoding, out fileNameExtension);
return new ReportsResult(renderedBytes, mimeType);
}

以及html的调用:

<div>
@{
Html.RenderAction("EmployeesNumberPerYear", "EmployeeReports");
}
</div>

其实问题就在于扩展的ActionResult,怎样将报表生成的RDLC转换过的二进制数据通过HttpContext来进行输出,并且RenderAction能够正确的显示出预览。

另外要说明的是,如果直接通过连接或url访问该action,excel的格式会直接用于保存,pdf的会显示出来。但我想让数据以预览的形式展示到div当中。



海绵宝宝撒
浏览 666回答 1
1回答

Helenr

EmployeesNumberPerYear是通过Ajax调用的吗?
随时随地看视频慕课网APP
我要回答