Objective
In most forms, there is the ability to export Excel tables, and if encapsulation encapsulates a class, it is not convenient to call this class directly when using it. , which also reduces the duplication of code, why not?
Operation
First add references in COM, select Microsoft Office 16.0 Object Library, and Microsoft Excel 16.0 Object Library.
To add a namespace:
Using microsoft.office.interop.excel;//export excelusing microsoft.office.core;using system.data.oledb;using System.Windows.Forms;
Create a new class and name it Outputexcel with the following code:
public class Outputexcel {//export Excel public void Rexcel (string name, DataGridView DGV) { Total visible row count int rowCount = DGV. Rows.getrowcount (datagridviewelementstates.visible); int colcount = DGV. Columns.getcolumncount (datagridviewelementstates.visible); If there is no data if (DGV. Rows.Count = = 0 | | RowCount = = 0) {MessageBox.Show ("No data in table", "hint"); } else {//path to create file SaveFileDialog save = new SaveFileDialog (); Save. Filter = "Excel Files (*.xlsx) |*.xlsx"; Save. Title = "Select the location where you want to export the data"; Save. FileName = name + DateTime.Now.ToLongDateString (); if (save. ShowDialog () = = DialogResult.OK) {string fileName = save. FileName; Create an Excel object Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel. Application (); if (Excel = = null) {MessageBox.Show ("Excel Cannot Start", "prompt"); Return }//Create workbook Microsoft.Office.Interop.Excel.Workbook Excelbook = Excel. Workbooks.Add (TRUE); Microsoft.Office.Interop.Excel.Worksheet ExcelSheet = (Microsoft.Office.Interop.Excel.Worksheet) EXCELBOOK.WORKSHEETS[1]; Generate field name int k = 0; for (int i = 0; i < DGV. ColumnCount; i++) {if (DGV. Columns[i]. Visible)//Do not export hidden columns {Excel. Cells[1, K + 1] = DGV. Columns[i]. HeaderText; k++; }}//Fill data for (int i = 0; i < DGV. RowCount; i++) {k = 0; for (iNT J = 0; J < DGV. ColumnCount; J + +) {if (DGV. COLUMNS[J]. Visible)//Do not export the hidden column {if (dgv[j, I]. ValueType = = typeof (String)) {Excel. Cells[i + 2, K + 1] = "" + dgv[j, I]. Value.tostring (); } else {Excel. Cells[i + 2, K + 1] = Dgv[j, I]. Value.tostring (); }} k++; }} try {excelbook.saved = true; Excelbook.savecopyas (FileName); MessageBox.Show ("Export succeeded! "); } catch {MessageBox.Show ("The Export file is missingThe file may be in use "," prompt "); } } } } }
When the form needs to use this feature, you need to write the following code:
private void Btnoutexcel_click (object sender, EventArgs e) { Outputexcel form1 = new Outputexcel (); Form1. Rexcel ("", DataGridView1); }
Related articles:
C # Tutorial C # data type
MySQL Connector/C + + multithreaded encapsulation