I have the following code:
private void CreateExcel(string fileName)
{
var operationDate = System.DateTime.ParseExact(txtStartDate.Text, "dd/MMM/yyyy", CultureInfo.CurrentCulture);
var ds1 = new _spAvailabilityEventDailyReport1TableAdapter();
var ds2 = new _spAvailabilityEventDailyReport2TableAdapter();
var ds3 = new _spAvailabilityEventDailyReport3TableAdapter();
var ds4 = new _spAvailabilityEventTotalTableAdapter();
var ds5 = new _spAvailabilityNoteDailyReportTableAdapter();
var ds6 = new _spAvailabilityDailyReportTableAdapter();
var ds7 = new _spAvailabilityReadingTotalTableAdapter();
var ds8 = new _spAvailabilityEventSum1TableAdapter();
var ds9 = new _spAvailabilityEventSum2TableAdapter();
var ds10 = new _spAvailabilityEventSum3TableAdapter();
//default margin setting
string outputType = "Excel";
string pageHeight = "11.69in";
string pageWidth = "8.27in";
string marginTop = "0.3937in";
string marginBottom = "0.3937in";
string marginLeft = "0.3937in";
string marginRight = "0.3937in";
string reportPath = Server.MapPath("~/rdlc/dailyavailability.rdlc");
try
{
//search setting margin report & kind output export -> for parameter 2nd render RDLC
var xml = System.IO.File.ReadAllText(reportPath);
var matches = Regex.Matches(xml, #"<(?<property>PageHeight|PageWidth|TopMargin|BottomMargin|LeftMargin|RightMargin)>(?<value>[^<]+)</\k<property>>", RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
if (!match.Success)
continue;
switch (match.Groups["property"].Value)
{
case "PageHeight":
pageHeight = match.Groups["value"].Value;
break;
case "PageWidth":
pageWidth = match.Groups["value"].Value;
break;
case "TopMargin":
marginTop = match.Groups["value"].Value;
break;
case "BottomMargin":
marginBottom = match.Groups["value"].Value;
break;
case "LeftMargin":
marginLeft = match.Groups["value"].Value;
break;
case "RightMargin":
marginRight = match.Groups["value"].Value;
break;
}
}
}
catch (System.Exception) { }
string reportType = string.IsNullOrEmpty(outputType) ? "Excel" : outputType.Trim().ToUpper();
string encoding;
string deviceInfo = string.Format(#"<DeviceInfo>
<OutputFormat>{6}</OutputFormat>
<PageWidth>{0}</PageWidth>
<PageHeight>{1}</PageHeight>
<MarginTop>{2}</MarginTop>
<MarginLeft>{3}</MarginLeft>
<MarginBottom>{4}</MarginBottom>
<MarginRight>{5}</MarginRight>
</DeviceInfo>", pageWidth, pageHeight, marginTop, marginLeft, marginBottom, marginRight, reportType);
var rds = new ReportDataSource("dsAvailabilityEventDailyReport1", (DataTable)ds1.GetData(operationDate)); //fill data report in parameter
var rds2 = new ReportDataSource("dsAvailabilityEventDailyReport2", (DataTable)ds2.GetData(operationDate)); //fill data report in parameter
var rds3 = new ReportDataSource("dsAvailabilityEventDailyReport3", (DataTable)ds3.GetData(operationDate)); //fill data report in parameter
var rds4 = new ReportDataSource("dsAvailabilityEventTotal", (DataTable)ds4.GetData(operationDate)); //fill data report in parameter
var rds5 = new ReportDataSource("dsAvailabilityNoteDailyReport", (DataTable)ds5.GetData(operationDate)); ///fill data report in parameter
var rds6 = new ReportDataSource("dsAvailabilityDailyReport", (DataTable)ds6.GetData(operationDate)); //fill data report in parameter
var rds7 = new ReportDataSource("dsAvailabilityReadingTotal", (DataTable)ds7.GetData(operationDate)); //fill data report in parameter
var rds8 = new ReportDataSource("dsAvailabilityEventSum1", (DataTable)ds8.GetData(operationDate)); //fill data report in parameter
var rds9 = new ReportDataSource("dsAvailabilityEventSum2", (DataTable)ds9.GetData(operationDate)); //fill data report in parameter
var rds10 = new ReportDataSource("dsAvailabilityEventSum3", (DataTable)ds10.GetData(operationDate)); //fill data report in parameter
// Variables
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string extension = string.Empty;
// Setup the report viewer object and get the array of bytes
var report = new LocalReport();
report.ReportPath = reportPath;
report.DataSources.Add(rds); // Add datasource here
report.DataSources.Add(rds2); // Add datasource here
report.DataSources.Add(rds3); // Add datasource here
report.DataSources.Add(rds4); // Add datasource here
report.DataSources.Add(rds5); // Add datasource here
report.DataSources.Add(rds6); // Add datasource here
report.DataSources.Add(rds7); // Add datasource here
report.DataSources.Add(rds8); // Add datasource here
report.DataSources.Add(rds9); // Add datasource here
report.DataSources.Add(rds10); // Add datasource here
//set parameter report (jika ada)
report.SetParameters(new List<ReportParameter>
{
//new ReportParameter("FacilitySubClassID", facilitySubClassId.ToString()),
new ReportParameter("OperationDate", operationDate.ToString())
});
byte[] bytes = report.Render(reportType, deviceInfo, 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=\"" + fileName + "." + extension + "\"");
Response.BinaryWrite(bytes); // create the file
Response.Flush(); // send it to the client to download
}
I have a sub-report on my rdlc report,, when i tried to export it to excel. The error message appear on excel file (sub-report section).
"Data retrieval failed for the subreport, 'srAvailabilityList', located at: C:\Users\xxxxx\Documents\Visual Studio 2010\Projects\coco\rdlc\availabilityreading.rdlc. Please check the log files for more information."
The sub-report is using ds6 and ds7.
My questions are:
How can I retrieve the data in the sub-report?
Where I can find the log files?
Found the answer:
void MySubreportEventHandler(object sender, SubreportProcessingEventArgs e)
{
var operationDate = System.DateTime.ParseExact(txtStartDate.Text, "dd/MMM/yyyy", CultureInfo.CurrentCulture);
var ds6 = new _spAvailabilityDailyReportTableAdapter();
var ds7 = new _spAvailabilityReadingTotalTableAdapter();
var rds6 = new ReportDataSource("dsAvailabilityDailyReport", (DataTable)ds6.GetData(operationDate)); //isi data report di parameter kedua
var rds7 = new ReportDataSource("dsAvailabilityReadingTotal", (DataTable)ds7.GetData(operationDate)); //isi data report di parameter kedua
e.DataSources.Add(rds6);
e.DataSources.Add(rds7);
}
Then add this code before report.SetParameter :
report.SubreportProcessing += new SubreportProcessingEventHandler(MySubreportEventHandler);
Related
Hi I am working on a MVC Project in which I have a reports page where user can view reports with the use of a report viewer.
I need to set the page size dynamically for a report, I tried many ways to solve this but I couldn’t.
I can change the ReportViewer Size with this code
rptviewer.Height = Unit.Pixel(520);
Kindly help me in with the following queries.
1.Is it possible to change the SSRS report page height using C# Code?
2.Is it possible to change the paper size in the runtime?
My Previous workarounds
<-------- 1 --------->
System.Drawing.Printing.PageSettings pg = new System.Drawing.Printing.PageSettings();
pg.Margins.Top = 0;
pg.Margins.Bottom = 0;
pg.Margins.Left = 0;
pg.Margins.Right = 0;
System.Drawing.Printing.PaperSize size = new PaperSize();
size.RawKind = (int)PaperKind.A5;
pg.PaperSize = size;
rptviewer.SetPageSettings(pg);
ViewBag.ReportViewer = rptviewer;
return View("_ReportView");
<-------- 2 --------->
System.Drawing.Printing.PageSettings MyPageSize= new System.Drawing.Printing.PageSettings();
MyPageSize.PaperSize = new System.Drawing.Printing.PaperSize("Custom", 17, 12);
rptviewer.SetPageSettings(MyPageSize);
<-------- 3 --------->
var setup = rptviewer.GetPageSettings();
setup.PaperSize.Height = 1500;
rptviewer.SetPageSettings(setup);
None of the above logic worked for me :-(
The thing is, In order to control the page size in the rendering process we need to pass the proper Device Information Settings to the report at run time. This will work for physical page oriented renders like PDF, Image, etc. This is a simple Xml string that can be passed as a parameter to the report in order to control these settings. Each export type has a different set of properties that can be overridden and controlled in this way.
In the following example, an export to PDF is performed and passes the page height and width to match an A4 paper size as the targeted device (line 66):
private void RenderReportToClient()
{
//set credentials
RSExecuteProxy.ReportExecutionService rs = new RSExecuteProxy.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
RSProxy.ReportingService2005 rsInfo = new RSProxy.ReportingService2005();
rsInfo.Credentials = System.Net.CredentialCache.DefaultCredentials;
// init render args
byte[] result = null;
string reportPath = rptViewer.ServerReport.ReportPath;
string format = "PDF";
string historyId = null;
string encoding;
string mimeType;
string extension;
RSExecuteProxy.Warning[] warnings = null;
string[] streamIDs = null;
//init exec info
RSExecuteProxy.ExecutionInfo execInfo = new RSExecuteProxy.ExecutionInfo();
RSExecuteProxy.ExecutionHeader execHeader = new RSExecuteProxy.ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
//get report
execInfo = rs.LoadReport(reportPath, historyId);
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
//get parameter info
ReportParameterInfoCollection parameters = rptViewer.ServerReport.GetParameters();
//figure out how many parameters we will have
//those with multi-value will need there own ParameterValue in the array
int paramCount = 0;
foreach (ReportParameterInfo pramInfo in parameters)
{
paramCount += pramInfo.Values.Count;
}
RSExecuteProxy.ParameterValue[] prams = new SSRSWeb.RSExecuteProxy.ParameterValue[paramCount];
int currentPramPosition = 0;
//set pram values
foreach (ReportParameterInfo pramInfo in parameters)
{
foreach (string pramValue in pramInfo.Values)
{
prams[currentPramPosition] = new SSRSWeb.RSExecuteProxy.ParameterValue();
prams[currentPramPosition].Label = pramInfo.Name;
prams[currentPramPosition].Name = pramInfo.Name;
prams[currentPramPosition].Value = pramValue;
currentPramPosition++;
}
}
rs.SetExecutionParameters(prams, "en-US");
//build the device settings (A4 8.3 × 11.7)
string deviceInfo = string.Format("<DeviceInfo><PageHeight>{0}</PageHeight><PageWidth>{1}</PageWidth></DeviceInfo>", "11.7in", "8.3in");
//get report bytes
result = rs.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
Response.ClearContent();
Response.AppendHeader("Content-Disposition", "inline;filename=report.pdf");
Response.AppendHeader("content-length", result.Length.ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(result);
Response.Flush();
Response.Close();
}
When the report is saved you can view the PDF and examine the properties and notice that the page height and width is 8.3in x 11.7in as specified.
This is my code.
public static string LoadPackage(DirectoryInfo outputDir, string name)
{
FileInfo newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
if (newFile.Exists)
{
newFile.Delete();
newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
}
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 1;
using (ExcelPackage package = new ExcelPackage())
{
LoadSheet(package, outputDir, name);
package.SaveAs(newFile);
}
return newFile.FullName;
}
And after that i call LoadSheet method in order to fill my excel file from tsv file.
public static void LoadSheet(ExcelPackage package, DirectoryInfo
outputDir, string name)
{
var ws = package.Workbook.Worksheets.Add("Content");
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 2;
format.SkipLinesEnd = 1;
var range = ws.Cells["A1"].LoadFromText(new
FileInfo(outputDir.FullName + "\\" + name), format,
TableStyles.Medium27, false);
}
And this is my code on button click event
if (BrowseFileUpload.HasFile)
{
var name = BrowseFileUpload.PostedFile.FileName;
InputTextBox.Text = name;
LoadData.LoadPackage(new
System.IO.DirectoryInfo("C:\\Users\\Nemanja\\Downloads"), name);
InfoLabel.Text = "Your data has been imported!!!";
InfoLabel.ForeColor = System.Drawing.Color.Blue;
InfoLabel.Font.Size = 20;
}
Everything is ok i create new excel file, sheet save it but it does not load data that i need it to load inside excel file. It's only empty file or i get a error the file is corrupted recover what you can.
Can someone figure out what can be a problem based on my explanation and this code. Thank you all good people.
I think that the problem may well be with the format of your source data. I've put together the following sample, based on your code, and it works fine.
var outFile = Path.ChangeExtension(filePath, ".xlsx");
using (var p = new ExcelPackage())
{
var fmt = new ExcelTextFormat();
fmt.Delimiter = '\t';
fmt.SkipLinesBeginning = 2;
fmt.SkipLinesEnd = 1;
fmt.EOL = ((char)10).ToString(); // THIS LINE FIXED THE PROBLEM (UNIX NEWLINE)
var ws = p.Workbook.Worksheets.Add("Imported Text");
ws.Cells[1, 1].LoadFromText(new FileInfo(filePath), fmt, TableStyles.Medium27, false);
p.SaveAs(new FileInfo(outFile));
}
Try running your data through this and see if you get the same issue or not.
UPDATED
The problem was a unix-style newline in the file - EPPlus expects a windows-style newline by default
I'm creating a pdf file this is my code:
public ActionResult ImprimirPedido()
{
List<ReporteModel> lista = new List<ReporteModel>();
ReporteModel obj = new ReporteModel();
obj.Responsable = "juan peres";
obj.TipoPago = "Efectivo";
obj.Fecha = "02/05/2014";
obj.NombreProducto = "chocolate";
obj.Cantidad = "2";
obj.Total = "54.00";
lista.Add(obj);
string directorio = "~/Models/";
string urlarchivo = string.Format("{0}.{1}", "Reporte_Disenio", "rdlc");
string fullpath = string.Format("{0}{1}", this.HttpContext.Server.MapPath(directorio), urlarchivo);
ReportViewer repor = new ReportViewer();
repor.Reset();
repor.LocalReport.ReportPath = fullpath;
ReportDataSource data = new ReportDataSource("DS_REPORT", lista);
repor.LocalReport.DataSources.Add(data);
repor.LocalReport.Refresh();
byte[] file = repor.LocalReport.Render("PDF");
return File(new MemoryStream(file).ToArray(),
System.Net.Mime.MediaTypeNames.Application.Octet,
string.Format("{0}{1}", "archivo.", "PDF"));
}
Now I want to print directly on the printer without preview, the printer is installed on my pc with iis. here run my systema mvc4 .net.
How to get the values from web.config (appsettings) file to my rdlc report?
I need to show multiple values in my rdlc invoice where they are coming from web.config file? How can I get on this one?
<add key="siteName" value="desktopapplications" />
<add key="companyName" value="ProSoftware Limited" />
where can I write the code in rdlc and how to implement the above values?
I know how to get the values from web.config to .cs page
string siteName= WebConfigurationManager.AppSettings["siteName"]
How it works in rdlc? Any help thanks
In the RDLC designer in the Report Data panel, add parameters for siteName and companyName. In the code behind:
Dim myReport As New LocalReport
Dim params() As ReportParameter = New ReportParameter(1) {}
params(0) = New ReportParameter("siteName", siteName)
params(1) = New ReportParameter("companyName", companyName)
With myReport
.ReportPath = ReportPath '"MyReport.rdlc"
.DataSources.Clear()
.DataSources.Add(mydatasource)
.Refresh()
.SetParameters(params)
End With
From Lon Prosser Answer
using (var lr = new LocalReport())
{
var path = Path.Combine(HttpRuntime.AppDomainAppPath, "Report", "MyInvoice.rdlc");
lr.ReportPath = path;
var siteName = ConfigurationManager.AppSettings["siteName"];
var companyName = ConfigurationManager.AppSettings["companyName"];
var #params = new ReportParameter[2];
#params[0] = new ReportParameter("siteName", siteName);
#params[1] = new ReportParameter("companyName",companyName);
var usersinv = db.Invoices.Where(i => i.Id == invoiceid.Id);
var invoice = usersinv.SingleOrDefault();
if (invoice != null)
{
var invoiceitems = db.InvoiceItems.Where(i => i.InvoiceId == invoiceid.Id);
var rd1 = new ReportDataSource("Invoice", usersinv);
var rd2 = new ReportDataSource("InvoiceItems", invoiceitems.ToList());
lr.DataSources.Add(rd1);
lr.DataSources.Add(rd2);
lr.SetParameters(#params);
}
string encoding;
string fileNameExtention;
const string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>21cm</PageWidth>" +
" <PageHeight>29.7cm</PageHeight>" +
" <MarginTop>0.0cm</MarginTop>" +
" <MarginLeft>0.0cm</MarginLeft>" +
" <MarginRight>0.0cm</MarginRight>" +
" <MarginBottom>0.0cm</MarginBottom>" +
"</DeviceInfo>";
Microsoft.Reporting.WebForms.Warning[] warnings;
string[] streams;
renderedBytes = lr.Render("PDF",
deviceInfo,
out mimeType,
out encoding,
out fileNameExtention,
out streams,
out warnings);
}
return File(renderedBytes, mimeType);
Now, the parameters in the PDF invoice will be invoked by web.config file
I had an grid view where I had placed an link button to print an report. In this button click event I need to call the SSRS report and need to get the output as PDF file.
I had used this below code,the code is running fine, but I'm unable to see the prompt to open/save pdf file.
protected void btnAuthenticateAndPrint_Click(object sender, EventArgs args)
{
try
{
//Getting Values from grid
LinkButton lb = (LinkButton)sender;
GridViewRow row = (GridViewRow)lb.NamingContainer;
Label lbOrderID = row.FindControl("lbOrderID") as Label;
int OrderId = Convert.ToInt32(lbOrderID.Text);
da = new SqlDataAdapter("Get_PODetails", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("#MPDI_ID", OrderId);
ds = new DataSet();
da.Fill(ds, "PO");
if (ds.Tables["PO"].Rows.Count > 0)
{
lblPOId.Text=ds.Tables["PO"].Rows[0]["MPDI_ID"].ToString();
lblVendid.Text = ds.Tables["PO"].Rows[0]["MVDI_ID"].ToString();
lblBranch.Text = ds.Tables["PO"].Rows[0]["MBRI_ID"].ToString();
lblDate.Text = Convert.ToDateTime(ds.Tables["PO"].Rows[0]["MPDI_Date"]).ToString("dd-MM-yyyy");
}
//SSRS Report Print
rs = new RSWebService.ReportingService2005();
rsExec = new REWebService.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://localhost/ReportServer/ReportService2005.asmx";
rsExec.Url = "http://localhost/ReportServer/ReportExecution2005.asmx";
byte[] Sendresults = null;
byte[] bytes = null;
string historyID = null;
string deviceInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string format = "PDF";
string encoding = null;
string mimeType = null;
string extension = null;
REWebService.Warning[] warnings = null;
string[] streamIDs = null;
string _reportName = #"/FIMO GOF Assets Reports/PURCHASE ORDER";
REWebService.ExecutionInfo ei = rsExec.LoadReport(_reportName, historyID);
REWebService.ParameterValue[] parameters = new REWebService.ParameterValue[4];
parameters[0] = new REWebService.ParameterValue();
parameters[0].Name = "MVDI_ID";
parameters[0].Value = lblVendid.Text;
parameters[1] = new REWebService.ParameterValue();
parameters[1].Name = "MBRI_ID";
parameters[1].Value = lblBranch.Text;
parameters[2] = new REWebService.ParameterValue();
parameters[2].Name = "MPDI_Date";
parameters[2].Value = lblDate.Text;
parameters[3] = new REWebService.ParameterValue();
parameters[3].Name = "ReportParameter1";
parameters[3].Value = lblPOId.Text;
rsExec.SetExecutionParameters(parameters, "en-us");
Sendresults = rsExec.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
MemoryStream ms = new MemoryStream(Sendresults);
//To create a PDF
if (format == "PDF")
{
Response.ContentType = "application/pdf";
Response.AddHeader("Content-disposition", "inline;filename=output.pdf");
Response.AddHeader("Content-Length", Sendresults.Length.ToString());
}
Response.OutputStream.Write(Sendresults, 0, Sendresults.Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
}
catch(Exception Ex)
{
throw Ex;
}
}
You can use URL access, as described here: http://msdn.microsoft.com/en-us/library/ms154040(v=sql.105).aspx
http://<Server Name>/reportserver?/Sales/YearlySalesSummary&rs:Format=PDF&rs:Command=Render