打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
在不预览的情况下打印本地报表

创建新的控制台应用程序项目

  1. “文件”菜单上,指向“新建”,然后选择“项目”

  2. “已安装的模板”窗格中,选择“C#”“Visual Basic”。根据 Visual Studio 中的启动设置,“C#”“Visual Basic”节点可能会显示在“其他语言”下。

  3. “模板”窗格中,选择“控制台应用程序”

  4. “名称”框中,键入项目的名称:“PrintLocalReport”

  5. “位置”框中,输入要保存项目的目录,或者单击“浏览”以导航到该目录。

  6. 单击“确定”。随即将打开项目,并在“代码”窗口中显示“Program”代码文件。

添加引用

  1. “项目”菜单中,选择“添加引用”

  2. “添加引用”对话框的“.NET”选项卡上,选择 System.DrawingSystem.Windows.FormsMicrosoft.ReportViewer.Winforms

  3. 单击“确定”

添加现有的 report.rdlc 和 data.xml 文件

  1. “项目”菜单中选择“添加现有项”。随即将显示“添加现有项”对话框。

  2. 定位到保存 report.rdlc 和 data.xml 的文件夹。然后选择这两个文件。

  3. 单击“添加”。这两个文件将作为项目的一部分显示在解决方案资源管理器中。

添加代码

  1. Program 代码文件应该已经打开并处于待编辑状态。如果该文件尚未打开,请在“解决方案资源管理器”窗口中双击“Program.cs”“Module1.vb”文件。

  2. 根据您的编程语言选择下面的代码,并用其替换“Program”文件中的现有代码。

    注意

    如果您的计算机上没有安装名为 Microsoft XPS Document Writer 的打印机,请将粗体代码更改为您计算机上的指定打印机。

    1. using System;
    2. using System.IO;
    3. using System.Data;
    4. using System.Text;
    5. using System.Drawing.Imaging;
    6. using System.Drawing.Printing;
    7. using System.Collections.Generic;
    8. using System.Windows.Forms;
    9. using Microsoft.Reporting.WinForms;
    10.  
    11. public class Demo : IDisposable
    12. {
    13.     private int m_currentPageIndex;
    14.     private IList<Stream> m_streams;
    15.  
    16.     private DataTable LoadSalesData()
    17.     {
    18.         // Create a new DataSet and read sales data file 
    19.         //    data.xml into the first DataTable.
    20.         DataSet dataSet = new DataSet();
    21.         dataSet.ReadXml(@"..\..\data.xml");
    22.         return dataSet.Tables[0];
    23.     }
    24.     // Routine to provide to the report renderer, in order to
    25.     //    save an image for each page of the report.
    26.     private Stream CreateStream(string name,
    27.       string fileNameExtension, Encoding encoding,
    28.       string mimeType, bool willSeek)
    29.     {
    30.         Stream stream = new MemoryStream();
    31.         m_streams.Add(stream);
    32.         return stream;
    33.     }
    34.     // Export the given report as an EMF (Enhanced Metafile) file.
    35.     private void Export(LocalReport report)
    36.     {
    37.         string deviceInfo =
    38.           @"<DeviceInfo>
    39.                 <OutputFormat>EMF</OutputFormat>
    40.                 <PageWidth>8.5in</PageWidth>
    41.                 <PageHeight>11in</PageHeight>
    42.                 <MarginTop>0.25in</MarginTop>
    43.                 <MarginLeft>0.25in</MarginLeft>
    44.                 <MarginRight>0.25in</MarginRight>
    45.                 <MarginBottom>0.25in</MarginBottom>
    46.             </DeviceInfo>";
    47.         Warning[] warnings;
    48.         m_streams = new List<Stream>();
    49.         report.Render("Image", deviceInfo, CreateStream,
    50.            out warnings);
    51.         foreach (Stream stream in m_streams)
    52.             stream.Position = 0;
    53.     }
    54.     // Handler for PrintPageEvents
    55.     private void PrintPage(object sender, PrintPageEventArgs ev)
    56.     {
    57.         Metafile pageImage = new
    58.            Metafile(m_streams[m_currentPageIndex]);
    59.  
    60.         // Adjust rectangular area with printer margins.
    61.         Rectangle adjustedRect = new Rectangle(
    62.             ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
    63.             ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
    64.             ev.PageBounds.Width,
    65.             ev.PageBounds.Height);
    66.  
    67.         // Draw a white background for the report
    68.         ev.Graphics.FillRectangle(Brushes.White, adjustedRect);
    69.  
    70.         // Draw the report content
    71.         ev.Graphics.DrawImage(pageImage, adjustedRect);
    72.  
    73.         // Prepare for the next page. Make sure we haven't hit the end.
    74.         m_currentPageIndex++;
    75.         ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
    76.     }
    77.  
    78.     private void Print()
    79.     {
    80.         if (m_streams == null || m_streams.Count == 0)
    81.             throw new Exception("Error: no stream to print.");
    82.         PrintDocument printDoc = new PrintDocument();
    83.         if (!printDoc.PrinterSettings.IsValid)
    84.         {
    85.             throw new Exception("Error: cannot find the default printer.");
    86.         }
    87.         else
    88.         {
    89.             printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
    90.             m_currentPageIndex = 0;
    91.             printDoc.Print();
    92.         }
    93.     }
    94.     // Create a local report for Report.rdlc, load the data,
    95.     //    export the report to an .emf file, and print it.
    96.     private void Run()
    97.     {
    98.         LocalReport report = new LocalReport();
    99.         report.ReportPath = @"..\..\Report.rdlc";
    100.         report.DataSources.Add(
    101.            new ReportDataSource("Sales", LoadSalesData()));
    102.         Export(report);
    103.         Print();
    104.     }
    105.  
    106.     public void Dispose()
    107.     {
    108.         if (m_streams != null)
    109.         {
    110.             foreach (Stream stream in m_streams)
    111.                 stream.Close();
    112.             m_streams = null;
    113.         }
    114.     }
    115.  
    116.     public static void Main(string[] args)
    117.     {
    118.         using (Demo demo = new Demo())
    119.         {
    120.             demo.Run();
    121.         }
    122.     }
    123. }

    Imports SystemImports System.IOImports System.DataImports System.TextImports System.DrawingImports System.Drawing.ImagingImports System.Drawing.PrintingImports System.Collections.GenericImports System.Windows.FormsImports Microsoft.Reporting.WinFormsPublic Class Demo    Implements IDisposable    Private m_currentPageIndex As Integer    Private m_streams As IList(Of Stream)    Private Function LoadSalesData() As DataTable        ' Create a new DataSet and read sales data file         ' data.xml into the first DataTable.        Dim dataSet As New DataSet()        dataSet.ReadXml("..\..\data.xml")        Return dataSet.Tables(0)    End Function    ' Routine to provide to the report renderer, in order to    ' save an image for each page of the report.    Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream        Dim stream As Stream = New MemoryStream()        m_streams.Add(stream)        Return stream    End Function    ' Export the given report as an EMF (Enhanced Metafile) file.    Private Sub Export(ByVal report As LocalReport)        Dim deviceInfo As String = "<DeviceInfo>" & _            "<OutputFormat>EMF</OutputFormat>" & _            "<PageWidth>8.5in</PageWidth>" & _            "<PageHeight>11in</PageHeight>" & _            "<MarginTop>0.25in</MarginTop>" & _            "<MarginLeft>0.25in</MarginLeft>" & _            "<MarginRight>0.25in</MarginRight>" & _            "<MarginBottom>0.25in</MarginBottom>" & _            "</DeviceInfo>"        Dim warnings As Warning()        m_streams = New List(Of Stream)()        report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)        For Each stream As Stream In m_streams            stream.Position = 0        Next    End Sub    ' Handler for PrintPageEvents    Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)        Dim pageImage As New Metafile(m_streams(m_currentPageIndex))        ' Adjust rectangular area with printer margins.        Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX), _                                          ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY), _                                          ev.PageBounds.Width, _                                          ev.PageBounds.Height)        ' Draw a white background for the report        ev.Graphics.FillRectangle(Brushes.White, adjustedRect)        ' Draw the report content        ev.Graphics.DrawImage(pageImage, adjustedRect)        ' Prepare for the next page. Make sure we haven't hit the end.        m_currentPageIndex += 1        ev.HasMorePages = (m_currentPageIndex < m_streams.Count)    End Sub    Private Sub Print()        If m_streams Is Nothing OrElse m_streams.Count = 0 Then            Throw New Exception("Error: no stream to print.")        End If        Dim printDoc As New PrintDocument()        If Not printDoc.PrinterSettings.IsValid Then            Throw New Exception("Error: cannot find the default printer.")        Else            AddHandler printDoc.PrintPage, AddressOf PrintPage            m_currentPageIndex = 0            printDoc.Print()        End If    End Sub    ' Create a local report for Report.rdlc, load the data,    ' export the report to an .emf file, and print it.    Private Sub Run()        Dim report As New LocalReport()        report.ReportPath = "..\..\Report.rdlc"        report.DataSources.Add(New ReportDataSource("Sales", LoadSalesData()))        Export(report)        Print()    End Sub    Public Sub Dispose() Implements IDisposable.Dispose        If m_streams IsNot Nothing Then            For Each stream As Stream In m_streams                stream.Close()            Next            m_streams = Nothing        End If    End Sub    Public Shared Sub Main(ByVal args As String())        Using demo As New Demo()            demo.Run()        End Using    End SubEnd Class

编译和运行应用程序

  1. “生成”菜单上单击“生成解决方案”以生成应用程序。在生成过程中,会编译报表并将发现的所有错误(例如报表中所用的表达式中的语法错误)都添加到“任务列表”中。

  2. “F5”运行应用程序。

    上面的代码会将报表打印到 .xps 文件并提示您输入文件位置。如果您指定打印设备的名称,该代码会将报表直接打印到该设备。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
[原创] RDLC 报表系列(一) 创建一个报表 - 大熊的空间 - 博客园
分页
VB实例教程之操作Access数据库
Flink资料(1)
dataset如何批量更新添加数据库
excel 导入导出 vb.net版,网上很难找的哦
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服