C#中使用FastReport写报告

在做一些数据类的应用时,经常需要统计,然后输出图表,需要导出或者打印。今天介绍一个适用的FastReport包。

一、FastReport的简单介绍

FastReport 是一个常用于 .NET(C# / WinForms / WPF / ASP.NET)的报表开发工具,用来生成各式各样的报表,比如PDF,数据统计报表,打印单据,图表等。其中PDF是最常见的,本文中也是输出PDF报告,报告中含有曲线图表的显示。
FastReport支持绑定数据,一键导出,包含丰富的报表组件,比如Text,Table,Picture,Chart,Line等,文章中会介绍部分组件的使用。
FastReport还支持可视化报表设计,因为博主的工程涉及到这部分,所以本文中没有对可视化报表设计的介绍。感兴趣的可以自行寻找资源,如若之后遇到,我还会再分享的。

二、NuGet 包安装

1、FastReport.DataVisualization
2、FastReport.OpenSource
3、FastReport.OpenSource.Export.PdfSimple
4、OxyPlot.Core(图表使用)
5、OxyPlot.WindowsForms(图表使用)
6、PdfiumViewer(PDF)
7、PdfiumViewer.Native.x86_64.v8-xfa(PDF)
我在开发中发现FastReport中很多属性都找不到,所以额外安装了部分包,这里仅供参考。

三、完整代码

老规矩,先贴全部代码吧,后面解析部分片段。

using FastReport;
using FastReport.Data;
using FastReport.DataVisualization.Charting;
using FastReport.Export.PdfSimple;
using FastReport.Table;
using OxyPlot;
using OxyPlot.Series;
using PdfiumViewer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DataPoint = OxyPlot.DataPoint;

namespace MyPro.report
{
    public partial class FormReport : Form
    {
        /// <summary>
        /// 报告
        /// </summary>
        private Report report; 

        /// <summary>
        /// PDF显示
        /// </summary>
        private PdfViewer pdfViewer;

        /// <summary>
        /// pdf暂存路径
        /// </summary>
        private string pdfPath;

        /// <summary>
        /// 报告页面
        /// </summary>
        private ReportPage page;

        /// <summary>
        /// 数据区
        /// </summary>
        private DataBand dataBand;

        /// <summary>
        /// 统一字体样式
        /// </summary>
        private static readonly Font Default12 = new Font("微软雅黑", 12);
        private static readonly Font Default10 = new Font("微软雅黑", 10);
        private static readonly Font Bold12 = new Font("微软雅黑", 12, FontStyle.Bold);

        public FormReport()
        {
            InitializeComponent();
            InitUI();
            InitReport();
        }

        /// <summary>
        /// 初始化UI(Panel内嵌PDF)
        /// </summary>
        private void InitUI()
        {
            page = new ReportPage();
            
            pdfViewer = new PdfViewer();
            pdfViewer.Dock = DockStyle.Fill;
            
            // rtPanelReportViewer是我自己写的Panel,用于显示pdfViewer
            rtPanelReportViewer.Controls.Clear();
            rtPanelReportViewer.Controls.Add(pdfViewer);
        }

        /// <summary>
        /// 初始化报表
        /// </summary>
        private void InitReport()
        {
            report = new Report();

            // ===== 创建页面(A4) =====
            report.Pages.Add(page);
            page.PaperWidth = 210;
            page.PaperHeight = 297;

            // ===== 标题 =====
            ReportTitleBand titleBand = new ReportTitleBand();
            titleBand.Height = 50;
            page.ReportTitle = titleBand;

            TextObject title = new TextObject();
            title.Bounds = new RectangleF(0, 0, 700, 40);
            title.Text = "测试报告";
            title.HorzAlign = HorzAlign.Center;
            title.Font = new Font("微软雅黑", 18, FontStyle.Bold);

            titleBand.Objects.Add(title);

            // ===== 个人信息 =====
            page.PageHeader = PersonalInfo();

            // ===== 数据区 =====
            dataBand = new DataBand();
            dataBand.Height = 600;
            dataBand.DataSource = report.GetDataSource("PageData");
            page.Bands.Add(dataBand);

            // ===== 曲线图 =====
            View_LineChart();

            // ===== 表格 =====
            View_Table();

            // ===== 准备报告 =====
            report.Prepare();

            // ===== 自动预览(用PDF)=====
            pdfPath = Path.Combine(Path.GetTempPath(), "report.pdf");

            PDFSimpleExport pdf = new PDFSimpleExport();
            report.Export(pdf, pdfPath);

            // ===== 显示到 Panel =====
            pdfViewer.Document = PdfDocument.Load(pdfPath);
        }

        /// <summary>
        /// 个人信息
        /// </summary>
        private PageHeaderBand PersonalInfo()
        {
            PageHeaderBand headerBand = new PageHeaderBand();
            headerBand.Height = 120;

            // 报告生成时间
            string timeStr = DateTime.Now.ToString("yyyy:MM:dd:HH:mm:ss");

            TextObject userInfo = new TextObject();
            userInfo.Bounds = new RectangleF(0, 0, 700, 30);
            userInfo.Text = "姓名:张三    年龄:25   性别:男";
            userInfo.Font = Default12;

            TextObject timeStrInfo = new TextObject();
            timeStrInfo.Bounds = new RectangleF(0, 30, 700, 30);
            timeStrInfo.Text = $"检测时间:{timeStr}";
            timeStrInfo.Font = Default12;
            
            headerBand.Objects.Add(userInfo);
            headerBand.Objects.Add(timeStrInfo);
            
            // 返回headerBand,可以让个人信息重复使用
            return headerBand;
        }

        /// <summary>
        /// 曲线图
        /// </summary>
        private void View_LineChart()
        {
            // ===== 1. 创建 PlotModel =====
            var model = new PlotModel 
            {
                Title = "曲线图",
                TitleFont = "微雅软黑",
                TitleFontSize = 12,
                TitleFontWeight = FontWeights.Bold,
            };

            var series = new LineSeries
            {
                Title = "曲线图",
                StrokeThickness = 2,
                Color = OxyColors.RoyalBlue,
            };

            // ===== 模拟数据=====
            Random rand = new Random();
            double x = 0;
            double y = 0;

            for (int i = 0; i < 100; i++)
            {
                x += rand.NextDouble() - 0.5;
                y += rand.NextDouble() - 0.5;
                series.Points.Add(new DataPoint(x, y));
            }

            model.Series.Add(series);

            // ===== 2. 导出为图片 =====
            var exporter = new OxyPlot.WindowsForms.PngExporter
            {
                Width = 300,
                Height = 300,
            };

            Image img;
            using (var ms = new MemoryStream())
            {
                exporter.Export(model, ms);
                ms.Seek(0, SeekOrigin.Begin);
                img = Image.FromStream(ms);
            }

            // ===== 3. 转为 FastReport 图片 =====
            var picture = new PictureObject();
            picture.Bounds = new RectangleF(0, 0, 300, 300); // 位置
            picture.Image = img;

            // ===== 4. 加到页面 =====
            dataBand1.Objects.Add(picture);
        }
        
        /// <summary>
        /// 表格
        /// </summary>
        private void View_Table()
        {
            DataTable table = new DataTable("TableData");
            // 列定义
            table.Columns.Add("Column1");
            table.Columns.Add("Column2");
            table.Columns.Add("Column3");
            table.Columns.Add("Column4");
            table.Columns.Add("Column5");
            table.Columns.Add("Column6");

            // 数据填充
            table.Rows.Add("数据1", "数据2", "数据3", "数据4", "数据5", "数据6");

            report.RegisterData(table, "TableData");

            TableObject tableObj = new TableObject();
            // 左边距,上边距,表格宽度,表格高度
            tableObj.Bounds = new RectangleF(0, 30, 720, 150);
            tableObj.RowCount = table.Rows.Count + 1; // +1 for header
            tableObj.ColumnCount = 6;

            // tableObj[列, 行]
            // 设置表头
            tableObj[0, 0].Text = "第一列数值";
            tableObj[1, 0].Text = "第二列数值";
            tableObj[2, 0].Text = "第三列数值";
            tableObj[3, 0].Text = "第四列数值";
            tableObj[4, 0].Text = "第五列数值";
            tableObj[5, 0].Text = "第六列数值";

            // 设置列宽
            for(int i = 0; i < 6; i++)
            {
                tableObj.Columns[i].Width = 120;
            }

            // 绑定数据
            for (int i = 0; i < table.Rows.Count; i++)
            {
                tableObj[0, i + 1].Text = table.Rows[i]["Column1"].ToString();
                tableObj[1, i + 1].Text = table.Rows[i]["Column2"].ToString();
                tableObj[2, i + 1].Text = table.Rows[i]["Column3"].ToString();
                tableObj[3, i + 1].Text = table.Rows[i]["Column4"].ToString();
                tableObj[4, i + 1].Text = table.Rows[i]["Column5"].ToString();
                tableObj[5, i + 1].Text = table.Rows[i]["Column6"].ToString();
            }

            // 修改表头样式
            for (int col = 0; col < tableObj.ColumnCount; col++)
            {
                tableObj[col, 0].Font = Bold12;
                tableObj[col, 0].Fill = new SolidFill(Color.FromArgb(246, 247, 249)); // 可选背景色
                tableObj[col, 0].HorzAlign = HorzAlign.Center;
                tableObj[col, 0].VertAlign = VertAlign.Center;
            }

            // 修改数据字体样式
            for (int row = 1; row < tableObj.RowCount; row++)
            {
                for (int col = 0; col < tableObj.ColumnCount; col++)
                {
                    tableObj[col, row].Font = Default10;
                    tableObj[col, row].HorzAlign = HorzAlign.Center;
                    tableObj[col, row].VertAlign = VertAlign.Center;
                }
            }

            // 增加边框
            tableObj.Border.Lines = BorderLines.All;
            tableObj.Border.Color = Color.Black;
            tableObj.Border.Width = 1;

            // 添加到数据带
            dataBand.Objects.Add(tableObj);
        }

        /// <summary>
        /// 打印报告
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rtButtonPrint_Click(object sender, EventArgs e)
        {
            if (File.Exists(pdfPath))
            {
                Process.Start(new ProcessStartInfo(pdfPath)
                {
                    Verb = "print",
                    UseShellExecute = true
                });
            }
        }

        /// <summary>
        /// 导出报告
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rtButtonExport_Click(object sender, EventArgs e)
        {
            if (report != null)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "PDF文件|*.pdf";

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    report.Export(new FastReport.Export.PdfSimple.PDFSimpleExport(), sfd.FileName);
                    MessageBox.Show("导出成功!");
                }
            }
        }
    }
}

四、代码片段解析

其实我觉得自己贴完全部代码也没有什么好解析的了,哈哈哈哈~感觉自己的备注还是比较详细的,嘻嘻。
不过为了更具体(实际为了凑字数),还是挑几段解析一下。

  1. 导出和打印报告

先解决一个可能的误会。

rtButtonPrint_Click(); rtButtonExport_Click();

这两个函数是我自己写的按钮点击事件,FastReport自带有“打印”和“导出”的,会显示在页面左上角,如图:
在这里插入图片描述

  1. 图表导出为图片

之所以要把 OxyPlot 图表转成图片,是因为 FastReport 本身不能直接渲染 OxyPlot 对象。
可以把OxyPlot理解为画图工具,FastReport只管显示绘画后的成果,不管绘画的过程。

// 创建导出器
// 这里的宽高就是在页面上导出的位置大小
 var exporter = new OxyPlot.WindowsForms.PngExporter
{
   Width = 300,
   Height = 300,
};
Image img;
using (var ms = new MemoryStream())
  {
      exporter.Export(model, ms);
      ms.Seek(0, SeekOrigin.Begin);
      img = Image.FromStream(ms);
  }

// ===== 3. 转为 FastReport 图片 =====
var picture = new PictureObject();
picture.Bounds = new RectangleF(0, 0, 300, 300); // 位置
picture.Image = img;

其中 RectangleF(0, 0, 300, 300);对应RectangleF(X轴偏移量, Y轴偏移量, 图片宽, 图片高);这里的图片宽高建议和导出器保持一致。

五、多页配置

一页显示不完怎么办?那就加页!

// 声明第二页
private ReportPage page2;
// 重点是记得声明第二页的数据区!
private DataBand dataBand2;
page2 = new ReportPage();
// 设置第二页的尺寸
page2.PaperWidth = 210;
page2.PaperHeight = 297;
// 初始化第二页数据区
dataBand2 = new DataBand();
dataBand2.Height = 600;
// 将第二页添加到报告中
report.Pages.Add(page2);
// 这样就可以将个人信息复用到第二页啦
page2.PageHeader = PersonalInfo();
// 绑定数据区
page2.Bands.Add(dataBand2);
// 往第二页数据区添加内容
dataBand2.Objects.Add(tableObj);

会添加一页就会添加第二页,注意声明数据区即可!添加内容的时候不要添加错数据区就好啦!

好了,本文先写到这里,感谢看完全文!比心!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HQL_seven

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值