日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

C#?Winform中DataGridView導(dǎo)出為Excel的實(shí)現(xiàn)示例_C#教程

作者:嵌入式悅翔園 ? 更新時(shí)間: 2022-07-03 編程語(yǔ)言

1、前言

話不多說(shuō),跟著我的步驟保證你也能成功,下面直接開(kāi)始!

2、效果展示

導(dǎo)出前

在這里插入圖片描述

導(dǎo)出后

在這里插入圖片描述

3、詳細(xì)步驟

下面是詳細(xì)操作步驟,請(qǐng)跟著我的步伐,一步一步進(jìn)行操作,保證你能夠?qū)С龀晒Γ?/p>

3.1 添加NPOI和NPOI.Excel包

首先請(qǐng)請(qǐng)確定你的vs已經(jīng)打開(kāi)了【解決方案資源管理器】,打開(kāi)步驟見(jiàn)下圖:

在這里插入圖片描述

在資源管理器中找到【引用】,然后在【引用】上右鍵選擇【管理程序包】并點(diǎn)擊,如下圖:

在這里插入圖片描述

在新打開(kāi)的窗口中點(diǎn)擊【瀏覽】并在搜索框中依次輸入NPOI和NPOI.Excel并進(jìn)行安裝,安裝按鈕位置如下圖:

在這里插入圖片描述

待安裝完成再進(jìn)行下一步

3.2 創(chuàng)建NPOIHelper類

首先在資源管理器中選中你的項(xiàng)目,【右鍵】找到【添加】–>【類】,具體如下圖:

在這里插入圖片描述

創(chuàng)建一個(gè)名字為【NPOIHelper.cs】的類并打開(kāi)

3.2.1 導(dǎo)入命名空間

復(fù)制下面的代碼,覆蓋你自動(dòng)生成的命名空間

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

3.2.2 插入代碼

將下面的代碼導(dǎo)入到下圖位置:

在這里插入圖片描述

public class ExcelUtility
        {
            /// <summary>
            /// 將excel導(dǎo)入到datatable
            /// </summary>
            /// <param name="filePath">excel路徑</param>
            /// <param name="isColumnName">第一行是否是列名</param>
            /// <returns>返回datatable</returns>
            public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
            {
                DataTable dataTable = null;
                FileStream fs = null;
                DataColumn column = null;
                DataRow dataRow = null;
                IWorkbook workbook = null;
                ISheet sheet = null;
                IRow row = null;
                ICell cell = null;
                int startRow = 0;
                try
                {
                    using (fs = File.OpenRead(filePath))
                    {
                        // 版本后綴控制
                        if (filePath.IndexOf(".xlsx") > 0)
                            workbook = new XSSFWorkbook(fs);
                        // 版本后綴控制
                        else if (filePath.IndexOf(".xls") > 0)
                            workbook = new HSSFWorkbook(fs);

                        if (workbook != null)
                        {
                            sheet = workbook.GetSheetAt(0);//讀取第一個(gè)sheet,當(dāng)然也可以循環(huán)讀取每個(gè)sheet
                            dataTable = new DataTable();
                            if (sheet != null)
                            {
                                int rowCount = sheet.LastRowNum;//總行數(shù)
                                if (rowCount > 0)
                                {
                                    IRow firstRow = sheet.GetRow(0);//第一行
                                    int cellCount = firstRow.LastCellNum;//列數(shù)

                                    //構(gòu)建datatable的列
                                    if (isColumnName)
                                    {
                                        startRow = 1;//如果第一行是列名,則從第二行開(kāi)始讀取
                                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                        {
                                            cell = firstRow.GetCell(i);
                                            if (cell != null)
                                            {
                                                if (cell.StringCellValue != null)
                                                {
                                                    column = new DataColumn(cell.StringCellValue);
                                                    dataTable.Columns.Add(column);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                                        {
                                            column = new DataColumn("column" + (i + 1));
                                            dataTable.Columns.Add(column);
                                        }
                                    }

                                    //填充行
                                    for (int i = startRow; i <= rowCount; ++i)
                                    {
                                        row = sheet.GetRow(i);
                                        if (row == null) continue;

                                        dataRow = dataTable.NewRow();
                                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                                        {
                                            cell = row.GetCell(j);
                                            if (cell == null)
                                            {
                                                dataRow[j] = "";
                                            }
                                            else
                                            {
                                                //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
                                                switch (cell.CellType)
                                                {
                                                    case CellType.Blank:
                                                        dataRow[j] = "";
                                                        break;
                                                    case CellType.Numeric:
                                                        short format = cell.CellStyle.DataFormat;
                                                        //對(duì)時(shí)間格式(2015.12.5、2015/12/5、2015-12-5等)的處理
                                                        if (format == 14 || format == 31 || format == 57 || format == 58)
                                                            dataRow[j] = cell.DateCellValue;
                                                        else
                                                            dataRow[j] = cell.NumericCellValue;
                                                        break;
                                                    case CellType.String:
                                                        dataRow[j] = cell.StringCellValue;
                                                        break;
                                                }
                                            }
                                        }
                                        dataTable.Rows.Add(dataRow);
                                    }
                                }
                            }
                        }
                    }
                    return dataTable;
                }
                catch (Exception)
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                    return null;
                }
            }
        }
        public static bool DataTableToExcel(DataTable dt, string txtPath)
        {
            bool result = false;
            IWorkbook workbook = null;
            FileStream fs = null;
            IRow row = null;
            ISheet sheet = null;
            ICell cell = null;
            try
            {
                if (dt != null && dt.Rows.Count > 0)
                {
                    workbook = new HSSFWorkbook();
                    sheet = workbook.CreateSheet("Sheet0");//創(chuàng)建一個(gè)名稱為Sheet0的表
                    int rowCount = dt.Rows.Count;//行數(shù)
                    int columnCount = dt.Columns.Count;//列數(shù)

                    //設(shè)置列頭
                    row = sheet.CreateRow(0);//excel第一行設(shè)為列頭
                    for (int c = 0; c < columnCount; c++)
                    {
                        cell = row.CreateCell(c);
                        cell.SetCellValue(dt.Columns[c].ColumnName);
                    }

                    //設(shè)置每行每列的單元格,
                    for (int i = 0; i < rowCount; i++)
                    {
                        row = sheet.CreateRow(i + 1);
                        for (int j = 0; j < columnCount; j++)
                        {
                            cell = row.CreateCell(j);//excel第二行開(kāi)始寫入數(shù)據(jù)
                            cell.SetCellValue(dt.Rows[i][j].ToString());
                        }
                    }
                    using (fs = File.OpenWrite(txtPath))
                    {
                        workbook.Write(fs);//向打開(kāi)的這個(gè)xls文件中寫入數(shù)據(jù)
                        result = true;
                    }
                }
                MessageBox.Show("導(dǎo)出成功");
                return result;
            }
            catch (Exception)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return false;
            }

        }

3.3 給畫面添加SaveFileDialog

首先在工具箱里找到SaveFileDialog(如果不知到工具箱在哪的可以點(diǎn)擊上方的【視圖】–> 【工具箱】)

在這里插入圖片描述

點(diǎn)住SaveFileDialog拖入頁(yè)面中效果如上圖所示

3.4 引入命名空間

將下方命名空間引入到你按鈕所在的cs中(主要是3、4)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;

3.5 給按鈕添加click事件

給按鈕添加click事件(直接雙擊按鈕即可),并在click函數(shù)中插入以下代碼

//打開(kāi)文件對(duì)話框,導(dǎo)出文件
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Title = "保存文件";
saveFileDialog1.Filter = "Excel 文件(*.xls)|*.xls|Excel 文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*";
saveFileDialog1.FileName = "用戶信息.xls"; //設(shè)置默認(rèn)另存為的名字
if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    string txtPath = this.saveFileDialog1.FileName;
    string sql = "select ID as ID,UserName as 用戶名,LoginAccount as 賬號(hào),UserPower as 用戶權(quán)限,Founder as 創(chuàng)建者,Addtime as 創(chuàng)建日期,Activestate as 狀態(tài) from UserData";
    SqlHelp sqlHelper = new SqlHelp();
    DataTable dt = sqlHelper.GetDataTableValue(sql);
    NPOIHelper.DataTableToExcel(dt, txtPath);
}

注意:上面的saveFileDialog1要和你視圖里的一樣一般沒(méi)問(wèn)題,sql語(yǔ)句我就不詳細(xì)講了不會(huì)的可以看我其他文章。

4、 成功

相信大家根據(jù)我的步驟應(yīng)該都能成功了,如果成功了別忘了三連哦!如果在操作過(guò)程中遇到什么問(wèn)題記得評(píng)論或者私信。

5、寫在最后

原文鏈接:https://blog.csdn.net/qq_45172832/article/details/124635582

欄目分類
最近更新