closedXML 操作excel

c#



//核心在于利用类DataSet和DataTable

/*

DataTable 类

.NET Framework (current version)
其他版本
 

表示内存中数据的一个表。

命名空间:    System.Data
程序集:  System.Data(位于 System.Data.dll)

DataSet 类

.NET Framework (current version)
其他版本
 

表示数据在内存中的缓存。

命名空间:    System.Data
程序集:  System.Data(位于 System.Data.dll)

closedXML类

可以通过NuGet搜索获取或者github上下载参考


*/
using System;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.Reflection;
using ClosedXML.Excel;//nuget 搜索closedXML 
namespace Export_DataTable_Excel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.BindDataGridView();
        }


        private void BindDataGridView()
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
            new DataColumn("Name", typeof(string)),
            new DataColumn("Country",typeof(string)) });
            dt.Rows.Add(1, "John Hammond", "United States");
            dt.Rows.Add(2, "Mudassar Khan", "India");
            dt.Rows.Add(3, "Suzanne Mathews", "France");
            dt.Rows.Add(4, "Robert Schidner", "Russia");
            this.dataGridView1.DataSource = dt;
        }


        private void btnExportExcel_Click(object sender, EventArgs e)
        {
            //Creating DataTable
            DataTable dt = new DataTable();


            //Adding the Columns
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                dt.Columns.Add(column.HeaderText, column.ValueType);
            }


            //Adding the Rows
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                dt.Rows.Add();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
                }
            }


            //Exporting to Excel
            string folderPath = "C:\\Excel\\";
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dt, "Customers");
                wb.SaveAs(folderPath + "DataGridViewExport.xlsx");
            }
        }
    }
}



你可能感兴趣的:(ADO,.NET)