I am using the following approach to create a dynamic Excel Report from HTML in my ASP.NET Application.
While creating the excel report, I want to set the Page Setup options such that the report fits into one page.
This is the approach I'm using to create the excel report...
Please tell me how to fit this report to one page or to zoom in the report?
string sContentType = "application/vnd.excel";
string sFileName = "Detail Qutation.xls";
Hashtable oData = new Hashtable();
oData.Add("Content-Disposition", "attachment;filename=" + sFileName);
oData.Add("Charset", "");
oData.Add("ContentType", sContentType);
oData.Add("Content", sTable.ToString());
oData.Add("IsBinaryContent", false);
this.StoreObject("Document", oData);
You might need to render using htmltextwriter as explained in
http://forums.asp.net/p/1063850/1538066.aspx#1538066
and take the concept to get a solution.
Related
I'm doing mvc reporting and i'm very new at it. I'm trying to create a report, and i have done it using rdlc. Everything works well, it can be exported to various format. My problem, when using rdlc is that we need to design and bind it first. How can i create an empty rdlc template, design and bind it with dataset programmatically.
My work so far (using empty rdlc template - just created the file without any table),
Controller File,
public ActionResult Report(string id)
{
DB.Open();
LocalReport lr1 = new LocalReport();
string path1 = Path.Combine(Server.MapPath("~/Report"), "TestEmptyReport.rdlc");
lr1.ReportPath = path1;
DataTable pc2a = new DataTable();
pc2a = DB.getDataSet().Tables[0];
pc2a.Columns.Add("Product Name");
pc2a.Columns.Add("Price");
pc2a.Columns.Add("Quantity");
ReportDataSource rdc = new ReportDataSource("DataSet1", pc2a);
lr1.DataSources.Add(rdc);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
"<OutputFormat>" + id + "</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 = lr1.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);
}
Model File,
public DataSet getDataSet()
{
string query = "SELECT * FROM tblproduct";
if (con.State.ToString() == "Open")
{
SqlDataAdapter ad = new SqlDataAdapter(query, con);
DataSet ds = new DataSet("tblproduct");
ad.Fill(ds);
return ds;
}
else
{
return null;
}
}
View File,
<div style="padding: 10px; border: 1px solid black">
<div>Get PDF Report</div>
<div>Get Excel Report</div>
<div>Get Word Report</div>
<div>Get Image Report</div>
The data is there, but i just dont know how to connect it with rdlc. Means creating column based on the data and fill it with the data called from sql server.
TQVM in advanced. Explanation and example or any other method will be helpful.
If I understand your question correctly you wanted to create a report from a blank RDLC. You have to tell a RDLC file about the data in the design time. You can customize the report in the design time by adding columns or columns from another table or make a join.
Whereas Dynamic RDLC Generator through C# would be there to generate the report dynamically from RDLC. Since the complete ReportingEngine has been custom made but very generic. Copy paste might be going to help generating the report.
Your question implies that you need to generate RDLC report on runtime mode. Things you should remember to:
RDLC report viewer uses Microsoft.ReportViewer.WebForms and Microsoft.Reporting.WebForms namespaces, which utilizing WebForms logic code to bind and render the report. You can use a partial view which acts as container for ASPX page (either using single page or page with code behind) to render the report in MVC view pages.
NB: You can use ReportViewer instance in controller action method to render RDLC as PDF file and returning FileContentResult (see here).
RDLC contains XML tags which can be generated from various XML builder classes (see MSDN Report Definition for details).
Hence, you may create ReportViewer instance first, e.g.:
using Microsoft.Reporting.WebForms;
protected void Form_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Report.rdlc");
// add your DataSet here
var data = new DataTable(); // example data source
var dataSource = new ReportDataSource(DataSetName, data);
ReportViewer1.LocalReport.DataSources.Add(dataSource);
// put rendering stuff here
}
}
Then, use steps from Generating RDLC Dynamically for the Report Viewer Local Report example (WebForms is similar to WinForms in terms of event handling usage, thus may be applicable in ASPX page) to create corresponding XML tags which generates report structure, summarized as below.
Create and add DataSet for usage in DataSources element.
Create report body and report items element.
Create Tablix and TablixCorner elements according to table structure inside DataSet.
Create TablixColumn, TablixRow and TablixCell elements which includes Textbox control depending to each column data types. The Value element inside Textbox control should contain expression =Fields!(ColumnName).Value for database-bound columns.
Create report property elements (dataset query, fields, etc.)
Add LoadReportDefinition into ASPX page after all report elements generated properly.
Alternatively, if you already know entire RDLC element structure, the similar solution using XmlWriter class can generate required elements for building the report from scratch, then rename generated XML to RDLC extension and bind it for ReportViewer control (seems takes some time to build each RDLC elements).
Additional references:
Rendering an RDLC report in HTML in ASP.NET MVC
Dynamic Reports with Reporting Services
Maybe this question was asked already feel free to point me to the right direction if it is.
I have a report on SSRS and my Dataset/Datasource is there of course. The Dataset is a Dynamic Query.
The idea is to export the result of the report via Excel.
I have a web server control ReportViewer in my Aspx. Does anyone knows if there is a method to export to excel and how I can code it in my code behind.
Please let me know if you need more info and I will post it.
EDIT:
Checking the info and the other links I did the following Method.
private void CreateEXCEL(Dictionary<string, string> parametros, string nombreReporte)
{
// Variables
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
List<ReportParameter> parameters = new List<ReportParameter>();
foreach (var d in parametros)
{
parameters.Add(new ReportParameter(d.Key, d.Value));
}
// Setup the report viewer object and get the array of bytes
MyReportViewer.ProcessingMode = ProcessingMode.Remote;
MyReportViewer.ServerReport.ReportPath = nombreReporte;
MyReportViewer.ServerReport.SetParameters(parameters);
byte[] bytes = MyReportViewer.ServerReport.Render("EXCEL", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
// Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=" + nombreReporte + "." + extension);
Response.BinaryWrite(bytes); // create the file
Response.Flush(); // send it to the client to download
}
But when I execute my web app and call this method I have the following error:
The Server commited a protocol infraction Section=ResponseStatusLine
Did anyone come accross a problem like this?
You can use .Render method:
LocalReport.Render
ServerReport.Render
The example provided by MSDN is for Excel but you can use the same method for PDF and any other supported formats.
Note that is also possible to manually export to Excel/PDF using the built-in functionality of ReportViewer.
Hi buddy if your columns are dynamic in the dataset then there is no such optio n in SSRS. But I can give you a hint like when you edit and SSRS it would like XML.
Keeping that in mind you can construct the entire structure of the dataset as an RDLC file from your code.
To be specific you need to generate RDLC file during runtime. Use the some common template and replace the template place holders with column value's
Personally I assure you it won't take much time to export the data. But you should put some effort to achieve this.
I'm telling this solution from my past experience. I have done something like this :)
Feel free to ask if you need more information. But don't ask code.
The Server commited a protocol infraction Section=ResponseStatusLine
Here's an answer that might help:
https://stackoverflow.com/a/4289266/3854195
I have some deployed SSRS reports on the server. Now I am accessing those reports from my ASP.NET application. After some research I found that default print button of the ReportViewer will not be visible in Chrome or any web browser except Internet Explorer. So all I want to render the Reports in PDF format so user can take the print out of PDF format without saving the file. Here's the piece of code I am using:
IReportServerCredentials irsc = DBConnection.NetworkCredentials();
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
List<ReportParameter> list = new List<ReportParameter>();
list.Add(new ReportParameter("ref_no", refNo));
ReportViewer1.ServerReport.SetParameters(list);
ReportViewer1.ServerReport.Render("PDF");
ReportViewer1.ServerReport.Refresh();
But its not working. The reports are getting rendered but not in PDF format. And if someone take the print out, alignment of all the fields like Tablix, TextBox are not properly aligned. Does any one know how can I do this?
Fortunately, after so many try, have found the solution. This is what I have done:
IReportServerCredentials irsc = DBConnection.NetworkCredentials();
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
List<ReportParameter> list = new List<ReportParameter>();
list.Add(new ReportParameter("ref_no", refNo));
ReportViewer1.ServerReport.SetParameters(list);
byte[] data = ReportViewer1.ServerReport.Render("pdf");
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline;filename=Manifest_Print.pdf");
Response.BinaryWrite(data);
And it worked for me.
Wondering what is a good library I can use with VS2005 to export data to a excel file. The file has some formatting like background colors and colspans.
Thanks
Here is some code that uses a trick to output HTML to an Excel file. I have found that you can trick excel into opening an HTML by setting the content type of the output to "application/excel".
In the code below secresults is an HTML div like so:
<div id="secresults" runat="server" visible="false" class="secresults">
Content or data here.
</div>
In code behind:
Response.ClearContent();
string filename = "Output" + istartDate.ToShortDateString() + ".xls";
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
secresults.RenderControl(htw);
Response.Write(sw.toString());
Response.End();
I have found that you can use some html formatting in excel. To test which formatting you can use you can create an html file and rename it to a .xls file, then open it with excel. You can get a pretty good idea about what HTML Excel will read.
I would recommend taking the class from the following website, and adapting it to your needs.
Mikes Knowledge Base - ExportToExcel
By default, this class takes a DataSet, DataTable or List<>, and exports it into a genuine Excel 2007 .xlsx file, using the OpenXML libraries (also provided).
It doesn't currently attempt to add any formating to the Excel cells (DataTables only store values, not formating, colors, horizontal alignment, etc !) but it should be a good place to start from.
All source code is provided, free of charge, so you can adapt it as required.
Good luck !
I have used this library in the past, but I normally just spit out a CSV file.
C# class library for exporting data to CSV/Excel file
If you have predefined layout of the document, Templater will probably fit your description.
Take a look at the example on how to use it.
I've used this codeplex project (Excel Package). One technique is to start with a formatted template, then modify the template. That is much easier than applying a lot of styling commands starting with an empty spreadsheet.
I have an html report having different sections like report header, report footer and the report data which needs to be exported to excel as it is. I am able to do this but the format of the report in excel is not proper. How can i make the format of the report as it is in the html report
i have used the following code to export html report with header and data to excel
Response.ContentType = "application/vnd.ms-excel";
string filename = "ECC_EMEA_" + String.Format("{0:dd_MMM_yy}", DateTime.Now.Date) + "_Summary.xls";
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
string htmlString = sb.ToString();
for (int i = 0; i < dt.Columns.Count;i++ )
Response.Write("\t"); ;
Response.Write(htmlString);
Response.End();
ms office html rendering engine is really limited... if you want excel to display report in a proper format you have to build it only with supported html elements, css...
from my experience and from what i remember something like this is not supported (had a similar task to yours)
<table STYLE="background-image:url('url')">
you have to google to see what other limitations are and what elements, css properties are supported.
EDITED
here I have found a msdn link. Word 2007 HTML and CSS Rendering Capabilities in Outlook 2007. Excel html, css limitations will be quite similar to this.