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當中。
添加回答
舉報
0/150
提交
取消