问题描述
|
我正在一个C#项目中,在该项目中,我从数据库生成报告,然后在DataGridView中显示,因为动态添加行和列更为简单。但是我现在需要将DataGridView内容即时导出到ReportViewer中以进行打印。我不想显示ReportViewer。我只想创建其实例并从DatagridView中填充,然后立即显示“打印对话框”,以在输出中获得高质量和组织良好的布局。目前,我正在通过将报告转换为HTML来打印报告,然后将其分配给Webbrowser控件并调用ShowPrintDialog()方法。但是以这种方式,由于Webbrowser顺序输出表,因此我无法控制某些打印问题,例如在所有页面中打印列标题。
我需要在最短的时间内达到这个目标,因为这是一个生产项目。
高度赞赏任何想法。
解决方法
您应该使用Microsoft Report Viewer
http://www.microsoft.com/zh-cn/download/details.aspx?id=3841
将dll文件添加到您的项目中:Microsoft.ReportViewer.Common和Microsoft.ReportViewer.WinForms,因此必须使用此文件创建* .rdlc文件,才能更改报告的设计。最后,为了节省它,您可以执行以下操作:
public static void PrintArticles(ICollectionView Articles)
{
try
{
var articlesRows = new DataTable(\"Articles\");
articlesRows.Columns.Add(\"Id\");
articlesRows.Columns.Add(\"Description\");
var arts = Articles.Cast<Article>();
foreach (var art in arts)
{
articlesRows.Rows.Add(art.Id,art.Description);
}
ReportViewer reporter = new ReportViewer();
reporter.LocalReport.DisplayName = \"Report1\";
reporter.LocalReport.ReportPath = Path.Combine(Program.BasePath + \"PrintArticles.rdlc\");
reporter.LocalReport.DataSources.Clear();
reporter.LocalReport.DataSources.Add(new ReportDataSource(\"Project1\",articlesRows));
byte[] report = reporter.LocalReport.Render(\"PDF\");
reporter.LocalReport.ReleaseSandboxAppDomain();
string pdfpath = Path.Combine(Program.BasePath,\"file.pdf\");
if (File.Exists(pdfpath))
File.Delete(Path.Combine(Program.BasePath,\"file.pdf\"));
FileStream writer = new FileStream(pdfpath,FileMode.Create);
writer.Write(report,report.Length);
writer.Close();
Process ar = Process.Start(pdfpath);
}
catch (Exception e)
{
}
}