Winform将DataGridView导出Excel,调用打印机打印DataGridView

DataGridView导出Excel

(这个需要 Microsoft.Office.Interop.Excel.dll  在网上下载就可以)

public static void ExportExcel(string fileName, DataGridView myDGV)
        {
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
            //写入标题
            for (int i = 0; i < myDGV.ColumnCount; i++)
            {
                worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
            }
            //写入数值
            for (int r = 0; r < myDGV.Rows.Count; r++)
            {
                for (int i = 0; i < myDGV.ColumnCount; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();//强行销毁
            MessageBox.Show("文件: " + fileName + ".xls 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

打印机打印DataGridView

1. 首先创建打印类

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Data;
using System.Windows.Forms;

namespace WCY_LAB {
public class GridPrinter
{
    // the grid to print
    private DataGridView dataGridView;
    // the PrintDocument
    private PrintDocument printDocument;
    // center printout?
    private bool centerOnPage;
    // has a title?
    private bool hasTitle;
    // title
    private string title;
    // font
    private Font titleFont;
    // title color
    private Color titleColor;
    // use paging?
    private bool paging;
    // row printing
    static int currentRow;
    // page printing
    static int pageNumber;
    // page width
    private int pageWidth;

    // page height
    private int pageHeight;
    // left margin
    private int leftMargin;
    // top margin
    private int topMargin;
    // right margin
    private int rightMargin;
    // bottom margin
    private int bottomMargin;
    // y location placeholder
    private float currentY;
    // grid sizes
    private float rowHeaderHeight;
    private List<float> rowsHeight;
    private List<float> columnsWidth;
    private float dataGridViewWidth;

    // column stop points
    private List<int[]> mColumnPoints;
    private List<float> mColumnPointsWidth;
    private int mColumnPoint;
    public GridPrinter(DataGridView objDataGridView, PrintDocument objPrintDocument, bool bCenterOnPage, bool bHasTitle, string sTitle, Font objTitleFont, Color objTitleColor, bool bPaging)
    {
        dataGridView = objDataGridView;
        printDocument = objPrintDocument;
        centerOnPage = bCenterOnPage;
        hasTitle = bHasTitle;
        title = sTitle;
        titleFont = objTitleFont;
        titleColor = objTitleColor;
        paging = bPaging;
        pageNumber = 0;
        rowsHeight = new List<float>();
        columnsWidth = new List<float>();
        mColumnPoints = new List<int[]>();
        mColumnPointsWidth = new List<float>();
        if (!printDocument.DefaultPageSettings.Landscape)
        {
            pageWidth = printDocument.DefaultPageSettings.PaperSize.Width;
            pageHeight = printDocument.DefaultPageSettings.PaperSize.Height;
        }
        else
        {
            pageHeight = printDocument.DefaultPageSettings.PaperSize.Width;
            pageWidth = printDocument.DefaultPageSettings.PaperSize.Height;
        }
        leftMargin = printDocument.DefaultPageSettings.Margins.Left;
        topMargin = printDocument.DefaultPageSettings.Margins.Top;
        rightMargin = printDocument.DefaultPageSettings.Margins.Right;
        bottomMargin = printDocument.DefaultPageSettings.Margins.Bottom;
        currentRow = 0;
    }
    // calculate printing metrics
    private void Calculate(Graphics g)
    {
        if (pageNumber == 0)
        {
            SizeF tmpSize = new SizeF();
            Font tmpFont;
            float tmpWidth;
            dataGridViewWidth = 0;
            for (int i = 0; i < dataGridView.Columns.Count; i++)
            {
                tmpFont = dataGridView.ColumnHeadersDefaultCellStyle.Font;
                if (tmpFont == null)
                    tmpFont = dataGridView.DefaultCellStyle.Font;
                tmpSize = g.MeasureString(dataGridView.Columns[i].HeaderText, tmpFont);
                tmpWidth = tmpSize.Width;
                rowHeaderHeight = tmpSize.Height;
                for (int j = 0; j < dataGridView.Rows.Count; j++)
                {
                    tmpFont = dataGridView.Rows[j].DefaultCellStyle.Font;
                    if (tmpFont == null)
                        tmpFont = dataGridView.DefaultCellStyle.Font;
                    tmpSize = g.MeasureString("Anything", tmpFont);
                    rowsHeight.Add(tmpSize.Height);
                    tmpSize = g.MeasureString(dataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont);
                    if (tmpSize.Width > tmpWidth)
                        tmpWidth = tmpSize.Width;
                }
                if (dataGridView.Columns[i].Visible)
                    dataGridViewWidth += tmpWidth;
                columnsWidth.Add(tmpWidth);
            }
            int k;
            int mStartPoint = 0;
            for (k = 0; k < dataGridView.Columns.Count; k++)
                if (dataGridView.Columns[k].Visible)
                {
                    mStartPoint = k;
                    break;
                }
            int mEndPoint = dataGridView.Columns.Count;
            for (k = dataGridView.Columns.Count - 1; k >= 0; k--)
                if (dataGridView.Columns[k].Visible)
                {
                    mEndPoint = k + 1;
                    break;
                }
            float mTempWidth = dataGridViewWidth;
            float mTempPrintArea = (float)pageWidth - (float)leftMargin - (float)rightMargin;

            if (dataGridViewWidth > mTempPrintArea)
            {
                mTempWidth = 0.0F;
                for (k = 0; k < dataGridView.Columns.Count; k++)
                {
                    if (dataGridView.Columns[k].Visible)
                    {
                        mTempWidth += columnsWidth[k];
                        if (mTempWidth > mTempPrintArea)
                        {
                            mTempWidth -= columnsWidth[k];
                            mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
                            mColumnPointsWidth.Add(mTempWidth);
                            mStartPoint = k;
                            mTempWidth = columnsWidth[k];
                        }
                    }
                    mEndPoint = k + 1;
                }
            }
            mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
            mColumnPointsWidth.Add(mTempWidth);
            mColumnPoint = 0;
        }
    }
    // header printing
    private void DrawHeader(Graphics g)
    {
        currentY = (float)topMargin;
        if (paging)
        {
            pageNumber++;
            string PageString = "Page " + pageNumber.ToString();
            StringFormat PageStringFormat = new StringFormat();
            PageStringFormat.Trimming = StringTrimming.Word;
            PageStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            PageStringFormat.Alignment = StringAlignment.Far;
            Font PageStringFont = new Font("Arial", 8, FontStyle.Regular, GraphicsUnit.Point);
            RectangleF PageStringRectangle = new RectangleF((float)leftMargin, currentY, (float)pageWidth - (float)rightMargin - (float)leftMargin, g.MeasureString(PageString, PageStringFont).Height);
            g.DrawString(PageString, PageStringFont, new SolidBrush(Color.Black), PageStringRectangle, PageStringFormat);
            currentY += g.MeasureString(PageString, PageStringFont).Height;
        }
        if (hasTitle)
        {
            StringFormat TitleFormat = new StringFormat();
            TitleFormat.Trimming = StringTrimming.Word;
            TitleFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            if (centerOnPage)
                TitleFormat.Alignment = StringAlignment.Center;
            else
                TitleFormat.Alignment = StringAlignment.Near;
            RectangleF TitleRectangle = new RectangleF((float)leftMargin, currentY, (float)pageWidth - (float)rightMargin - (float)leftMargin, g.MeasureString(title, titleFont).Height);
            g.DrawString(title, titleFont, new SolidBrush(titleColor), TitleRectangle, TitleFormat);
            currentY += g.MeasureString(title, titleFont).Height;
        }
        float CurrentX = (float)leftMargin;
        if (centerOnPage)
            CurrentX += (((float)pageWidth - (float)rightMargin - (float)leftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;
        Color HeaderForeColor = dataGridView.ColumnHeadersDefaultCellStyle.ForeColor;
        if (HeaderForeColor.IsEmpty)
            HeaderForeColor = dataGridView.DefaultCellStyle.ForeColor;
        SolidBrush HeaderForeBrush = new SolidBrush(HeaderForeColor);
        Color HeaderBackColor = dataGridView.ColumnHeadersDefaultCellStyle.BackColor;
        if (HeaderBackColor.IsEmpty)
            HeaderBackColor = dataGridView.DefaultCellStyle.BackColor;
        SolidBrush HeaderBackBrush = new SolidBrush(HeaderBackColor);
        Pen TheLinePen = new Pen(dataGridView.GridColor, 1);
        Font HeaderFont = dataGridView.ColumnHeadersDefaultCellStyle.Font;
        if (HeaderFont == null)
            HeaderFont = dataGridView.DefaultCellStyle.Font;
        RectangleF HeaderBounds = new RectangleF(CurrentX, currentY, mColumnPointsWidth[mColumnPoint], rowHeaderHeight);
        g.FillRectangle(HeaderBackBrush, HeaderBounds);
        StringFormat CellFormat = new StringFormat();
        CellFormat.Trimming = StringTrimming.Word;
        CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
        RectangleF CellBounds;
        float ColumnWidth;
        for (int i = (int)mColumnPoints[mColumnPoint].GetValue(0); i < (int)mColumnPoints[mColumnPoint].GetValue(1); i++)
        {
            if (!dataGridView.Columns[i].Visible) continue;
            ColumnWidth = columnsWidth[i];
            if (dataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Right"))
                CellFormat.Alignment = StringAlignment.Far;
            else if (dataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Center"))
                CellFormat.Alignment = StringAlignment.Center;
            else
                CellFormat.Alignment = StringAlignment.Near;
            CellBounds = new RectangleF(CurrentX, currentY, ColumnWidth, rowHeaderHeight);
            g.DrawString(dataGridView.Columns[i].HeaderText, HeaderFont, HeaderForeBrush, CellBounds, CellFormat);
            if (dataGridView.RowHeadersBorderStyle != DataGridViewHeaderBorderStyle.None)
                g.DrawRectangle(TheLinePen, CurrentX, currentY, ColumnWidth, rowHeaderHeight);
            CurrentX += ColumnWidth;
        }
        currentY += rowHeaderHeight;
    }
    // common row printing function
    private bool DrawRows(Graphics g)
    {
        Pen TheLinePen = new Pen(dataGridView.GridColor, 1);
        Font RowFont;
        Color RowForeColor;
        Color RowBackColor;
        SolidBrush RowForeBrush;
        SolidBrush RowBackBrush;
        SolidBrush RowAlternatingBackBrush;
        StringFormat CellFormat = new StringFormat();
        CellFormat.Trimming = StringTrimming.Word;
        CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit;
        RectangleF RowBounds;
        float CurrentX;
        float ColumnWidth;
        while (currentRow < dataGridView.Rows.Count)
        {
            if (dataGridView.Rows[currentRow].Visible)
            {
                RowFont = dataGridView.Rows[currentRow].DefaultCellStyle.Font;
                if (RowFont == null)
                    RowFont = dataGridView.DefaultCellStyle.Font;
                RowForeColor = dataGridView.Rows[currentRow].DefaultCellStyle.ForeColor;
                if (RowForeColor.IsEmpty)
                    RowForeColor = dataGridView.DefaultCellStyle.ForeColor;
                RowForeBrush = new SolidBrush(RowForeColor);
                RowBackColor = dataGridView.Rows[currentRow].DefaultCellStyle.BackColor;
                if (RowBackColor.IsEmpty)
                {
                    RowBackBrush = new SolidBrush(dataGridView.DefaultCellStyle.BackColor);
                    RowAlternatingBackBrush = new SolidBrush(dataGridView.AlternatingRowsDefaultCellStyle.BackColor);
                }
                else
                {
                    RowBackBrush = new SolidBrush(RowBackColor);
                    RowAlternatingBackBrush = new SolidBrush(RowBackColor);
                }
                CurrentX = (float)leftMargin;
                if (centerOnPage)
                    CurrentX += (((float)pageWidth - (float)rightMargin - (float)leftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;
                RowBounds = new RectangleF(CurrentX, currentY, mColumnPointsWidth[mColumnPoint], rowsHeight[currentRow]);
                if (currentRow % 2 == 0)
                    g.FillRectangle(RowBackBrush, RowBounds);
                else
                    g.FillRectangle(RowAlternatingBackBrush, RowBounds);
                for (int CurrentCell = (int)mColumnPoints[mColumnPoint].GetValue(0); CurrentCell < (int)mColumnPoints[mColumnPoint].GetValue(1); CurrentCell++)
                {
                    if (!dataGridView.Columns[CurrentCell].Visible) continue;
                    if (dataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Right"))
                        CellFormat.Alignment = StringAlignment.Far;
                    else if (dataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Center"))
                        CellFormat.Alignment = StringAlignment.Center;
                    else
                        CellFormat.Alignment = StringAlignment.Near;

                    ColumnWidth = columnsWidth[CurrentCell];
                    RectangleF CellBounds = new RectangleF(CurrentX, currentY, ColumnWidth, rowsHeight[currentRow]);
                    g.DrawString(dataGridView.Rows[currentRow].Cells[CurrentCell].EditedFormattedValue.ToString(), RowFont, RowForeBrush, CellBounds, CellFormat);

                    if (dataGridView.CellBorderStyle != DataGridViewCellBorderStyle.None)
                        g.DrawRectangle(TheLinePen, CurrentX, currentY, ColumnWidth, rowsHeight[currentRow]);
                    CurrentX += ColumnWidth;
                }
                currentY += rowsHeight[currentRow];
                if ((int)currentY > (pageHeight - topMargin - bottomMargin))
                {
                    currentRow++;
                    return true;
                }
            }
            currentRow++;
        }
        currentRow = 0;
        mColumnPoint++;
        if (mColumnPoint == mColumnPoints.Count)
        {
            mColumnPoint = 0;
            return false;
        }
        else
            return true;
    }
    // the main grid printing method
    public bool DrawDataGridView(Graphics g)
    {
        try
        {
            Calculate(g);
            DrawHeader(g);
            bool bContinue = DrawRows(g);
            return bContinue;
        }
        catch (Exception ex)
        {
            MessageBox.Show("ERROR: " + ex.Message.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }
    }
}
}

2. 添加PrintDocument控件,并且绑定PrintPage事件(gridPrinter是全局变量,在下面初始化)

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            bool more = gridPrinter.DrawDataGridView(e.Graphics);
            if (more == true)
                e.HasMorePages = true;
        }

3. 初始化打印类

       private bool InitializePrinting()
        {
            PrintDialog printDialog = new PrintDialog();
            if (printDialog.ShowDialog() != DialogResult.OK)
                return false;
            printDocument1.DocumentName = "历史信息";
            printDocument1.PrinterSettings = printDialog.PrinterSettings;
            printDocument1.DefaultPageSettings = printDialog.PrinterSettings.DefaultPageSettings;
            printDocument1.DefaultPageSettings.Margins = new Margins(40, 40, 40, 40);
            gridPrinter = new GridPrinter(dataGridView1, printDocument1, true, true, "历史信息", new Font("黑体", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Blue, true);
            return true;
        }

4. 按钮调用

	private void btnPrint_Click(object sender, EventArgs e)
        {
            if (InitializePrinting())
            {
                PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
                printPreviewDialog.Document = printDocument1;
                printPreviewDialog.ShowDialog();
            }
        }
时间: 2024-10-26 22:49:31

Winform将DataGridView导出Excel,调用打印机打印DataGridView的相关文章

.Net常用技巧_导出 Excel 和相关打印设置

Excel.Application myExcel = new Excel.Application();发 表Excel.Workbook workbookData = myExcel.Application.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);Excel.Worksheet xlSheet = (Worksheet)workbookData.Worksheets[1];//取得sheet1 1) 显示当前窗口: xlSheet.

C# 调用打印机打印文件

C# 调用打印机打印文件,通常情况下,例如Word.Excel.PDF等可以使用一些对应的组件进行打印,另一个通用的方式是直接启用一个打印的进程进行打印.示例代码如下: using System.Diagnostics; string filePath = "文件路径"; string printer = "打印机"; ProcessStartInfo info = new ProcessStartInfo(); info.Arguments = "\&q

Java jacob调用打印机打印word文档

前面说了Java如何生成复杂的Word文档,今年记录下Java如何调用打印机打印word文档. 起初用的是自带的PrintJob,但是系统提供的打印机制比不成熟完整.网上的代码也是千篇一律,在我的打印设备Canon iR2525/2530 UFRII LT上,我能获取到打印机的各属性,当前任务数.但是打印机没反应. 可参考这两篇文章: http://www.360doc.com/content/05/0916/11/332_12789.shtml http://www.ibm.com/devel

NPOI DataGridView导出EXCEL

NPOI 官方网站 http://npoi.codeplex.com/ 加载NPOI.DLL ,引用这两个命名空间 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; #region NPOI DataGridView 导出 EXCEL /// <summary> /// NPOI DataGridView 导出 EXCEL /// </summary> /// <param name="fileName"

从DataGridView导出Excel

从DataGridView导出Excel的两种情况,不多说,直接记录代码. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Data; namespace cnblogs { public static class LoadExcel { public sta

C#winform中datagridview导出Excel

只需要传入datagridview的name即可. 1 //导出Excel()方法 2 public void ToExcel(DataGridView dataGridView) 3 { 4 //实例化一个Excel.Application对象 5 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 6 7 if (excel == null)

Winform DataGridView导出Excel

private void 导出excelToolStripMenuItem_Click(object sender, EventArgs e) { if (dgvData.RowCount > 0) { var saveFileDialog1 = new SaveFileDialog { Filter = @"Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx", RestoreDirectory = true }; if (saveFileDialog1.Sh

DataGridView导出Excel

把DataGridView中的信息导出到Excel是<机房收费系统>的功能之一,这里主要是VS与Office的交互,方法有n多种(从这里就可以看出这个功能难不到哪里去了),现在就介绍一下我使用的一种吧,首先需要添加并引用命名空间. 1.添加:右击窗体所在的项目名即U层的项目名--添加--引用--出现下面图片,搜索Excel,在结果中选中符合版本的Microsoft.Interop.Excel 2.引用命名空间:Imports Microsoft.Office.Interop 由于多次用到了导出

winform 数据库资料导出Excel方法(适用于资料数据较多加载慢,不用呈现至DatagridView)

Private Sub savefile(ByVal dgv2 As DataTable) Dim app As Object = CreateObject("Excel.Application") Dim xlbook As Object = app.workbooks.add() Dim xR As Integer = dgv2.Rows.Count Dim xC As Integer = dgv2.Columns.Count Dim maxR As Integer = 20000