如何从 C# 中的 DataGridView 打印数据? [英] How can I print data from a DataGridView in C#?

查看:84
本文介绍了如何从 C# 中的 DataGridView 打印数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个程序,我需要打印显示在 DataGridView 控件中的 Bills 数据.
我想知道如何在DataGridView中打印数据的代码.

I am developing a program, and I need to print the Bills data that is displayed in a DataGridView control.
I want to know the code how to print the data in the DataGridView.

我使用的是 Visual Studio 2008 和 C# 3.5

I am using Visual Studio 2008 and C# 3.5

推荐答案

DataGridView 没有内置任何打印支持,因此您必须自己实现.有几种可能的解决方案:

There isn't any printing support built into the DataGridView, so you'll have to implement this yourself. There are a couple of possible solutions:

  1. WinForms 确实提供了一个标准的打印系统,您可以利用它来打印DataGridView 控件的内容.您需要使用 PrintDocument 类,因此相关的 文档 是开始阅读的好地方.这种方法的优点是它允许您完全控制打印文档的格式和布局.

  1. WinForms does provide a standard printing system, which you can harness to print out the contents of your DataGridView control. You'll want to use the PrintDocument class, so the relevant documentation is a great place to start reading. The advantage of this method is that it allows you complete control over the format and layout of the printed document.

您可以将 DataGridView 中的数据导出到 Microsoft Excel,然后从那里打印出来.Excel 具有更强大的内置打印支持.

You could export the data from your DataGridView to Microsoft Excel, and then print it from there. Excel has much more robust, built-in printing support.

如果您对推出自己的解决方案不感兴趣,可以浏览 CodeProject 以了解一些已经设计好的解决方案.例如:

If you're not interested in rolling your own solution, you can browse CodeProject for some already designed solutions. For example:

即使您没有找到适合您确切需求的插入式解决方案,您也可以通过使用已发布的代码作为示例来了解如何自己创建此功能.

Even if you don't find a drop-in solution that fits your exact needs, you can probably get a good idea of how to go about creating this functionality yourself by using the published code as an example.

如果您想要一个非常笨拙的解决方案(并且您没有任何愿望或需要自定义打印输出的布局或设计),您可以使用 DrawToBitmap 每个控件公开的方法.这是一种非常快速和肮脏的方法,它在 DataGridView 控件出现在您的屏幕上时将它的精确图像绘制为 Bitmap,然后您可以将其直接传递给您的打印机.

If you're up for a really hacky solution (and you don't have any desire or need to customize the layout or design of the printed output), you could use the DrawToBitmap method exposed by every control. This is a really quick-and-dirty approach that draws an exact image of the DataGridView control as it appears on your screen to a Bitmap, which you can then pass directly to your printer.

这篇关于如何从 C# 中的 DataGridView 打印数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆