WinForm Export DataGridView to Excel, call printer print DataGridView

Source: Internet
Author: User

DataGridView Exporting Excel

(This need Microsoft.Office.Interop.Excel.dll download on the internet can be)

public static void Exportexcel (String fileName, DataGridView mydgv) {string savefilename = "";            SaveFileDialog Savedialog = new SaveFileDialog ();            Savedialog.defaultext = "xls";            Savedialog.filter = "Excel file |*.xls";            Savedialog.filename = FileName;            Savedialog.showdialog ();            Savefilename = Savedialog.filename; if (Savefilename.indexof (":") < 0) return;            was ordered to cancel Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application ();                if (xlapp = = null) {MessageBox.Show ("Unable to create Excel object, may not have Excel installed on your machine");            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];//get Sheet1//write header for (int i = 0; i < Mydgv.columncount; i++) { Worksheet. Cells[1, i + 1] = Mydgv.columns[i].            HeaderText;  }//write value 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 ();//Column width adaptive if (savefilename! = "") {try { Workbook.                    Saved = true; Workbook.                SaveCopyAs (Savefilename); } catch (Exception ex) {MessageBox.Show ("Error exporting file, file may be open! \ n "+ ex.                Message);        }            }    xlApp.Quit (); Gc. Collect ();//forcibly Destroy MessageBox.Show ("file:" + FileName + ". xls saved successfully", "Informational tip", MessageBoxButtons.OK, MessageBoxIcon.        Information); }


Printer Print DataGridView


1. First create a print class

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{//T    He 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.PaperS Ize.            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 (Datagridvie        W.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, C                    Urrentx, 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 {Calc            Ulate (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. Add the PrintDocument control and bind the PrintPage event (Gridprinter is a global variable, initialized below)

        private void Printdocument1_printpage (object sender, System.Drawing.Printing.PrintPageEventArgs e)        {            bool more = Gridprinter.drawdatagridview (e.graphics);            if (more = = True)                E.hasmorepages = true;        }

3. Initialize the Print class

       private bool Initializeprinting ()        {            PrintDialog PrintDialog = new PrintDialog ();             if (printdialog.showdialog () = DialogResult.OK)                return false;            Printdocument1.documentname = "historical Information";            Printdocument1.printersettings = printdialog.printersettings;            Printdocument1.defaultpagesettings = printDialog.PrinterSettings.DefaultPageSettings;            PrintDocument1.DefaultPageSettings.Margins = new Margins (max, Max, +);            Gridprinter = new Gridprinter (DataGridView1, PrintDocument1, True, True, "historical information", New Font ("bold", FontStyle.Bold Csunit.point), Color.Blue, true);            return true;        }

4. Button call

private void Btnprint_click (object sender, EventArgs e)        {            if (initializeprinting ())            {                PrintPreviewDialog PrintPreviewDialog = new PrintPreviewDialog ();                Printpreviewdialog.document = printDocument1;                Printpreviewdialog.showdialog ();            }        }






WinForm Export DataGridView to Excel, call printer print DataGridView

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.