C# | Export data in DataGridView to Excel, CSV, TXT

insert image description here

C# | Export data in DataGridView to Excel, CSV, TXT

foreword

Exporting the data in DataGridView to Excel, CSV, and TXT is a frequently encountered requirement in development. It is a common way to convert the data in DataGridView to DataTable format first, and then export it. This article will introduce how to convert the data in DataGridView to DataTable format, and provide examples of converting DataTable to Excel, CSV, and TXT formats.

Converting the data in DataGridView to DataTable format will help us to process and operate the data more conveniently. By converting the data in DataGridView to DataTable format, we can easily use various data processing and operation functions in C#, such as sorting, filtering, statistics, etc. At the same time, converting data into DataTable format can also improve the readability and maintainability of data , making it easier for us to understand and manage data.

In this article, we will take actual code examples as an example to demonstrate how to convert data in DataGridView to DataTable format, and provide examples of converting DataTable to Excel, CSV, and TXT formats. Through the introduction and examples in this article, you will be able to quickly master the skills of exporting data in DataGridView to various formats, improving your development efficiency and code quality.

DataGridView data dump DataTable

Here is the idea of ​​conversion:

  1. First a new DataTable object is created.
  2. Then we added the DataTable columns using the DataGridView's column headers and value types.
  3. Next, we created new DataRow objects using the DataGridView's row and cell values ​​and added them to the DataTable.
            // 创建一个新的DataTable对象
            DataTable dt = new DataTable();

            // 添加列
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
    
    
                dt.Columns.Add(column.HeaderText, column.ValueType);
            }

            // 添加行
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
    
    
                DataRow dr = dt.NewRow();
                foreach (DataGridViewCell cell in row.Cells)
                {
    
    
                    dr[cell.ColumnIndex] = cell.Value;
                }
                dt.Rows.Add(dr);
            }

DataTable to Excel

Method 1. Use Microsoft.Office.Interop.Excel

Add citation:

using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

Dump the DataTable as an Excel file:

        public static void Convert(DataTable dt, string filePath)
        {
    
    
            // 创建一个Excel应用程序对象
            Excel.Application excelApp = new Excel.Application();

            // 创建一个新的工作簿
            Excel.Workbook workbook = excelApp.Workbooks.Add(Type.Missing);

            // 创建一个新的工作表并命名为“Sheet1”
            Excel.Worksheet worksheet = (Excel.Worksheet)workbook.ActiveSheet;
            worksheet.Name = "Sheet1";

            // 将DataTable的列名写入工作表中
            for (int i = 0; i < dt.Columns.Count; i++)
            {
    
    
                worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
            }

            // 将DataTable的数据写入工作表中
            for (int i = 0; i < dt.Rows.Count; i++)
            {
    
    
                for (int j = 0; j < dt.Columns.Count; j++)
                {
    
    
                    worksheet.Cells[i + 2, j + 1] = dt.Rows[i][j];
                }
            }

            // 保存工作簿
            workbook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            // 关闭工作簿和Excel应用程序对象
            workbook.Close();
            excelApp.Quit();

            // 释放Excel对象
            System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
        }

Method 2. Use the EPPlus library

Install the EPPlus library via NuGet:

In Visual Studio, you can use the NuGet package manager to add the EPPlus library. Just right-click "References" in the project, then select "Manage NuGet Packages", and search for "EPPlus" in the search box to find the EPPlus library, and choose to install it.

Dump the DataTable as an Excel file:

        public static void Convert(DataTable dt, string filePath)
        {
    
    
            // 创建一个新的Excel工作簿
            ExcelPackage excelPackage = new ExcelPackage();

            // 创建一个新的工作表并命名为“Sheet1”
            ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet1");

            // 将DataTable的列名写入工作表中
            for (int i = 0; i < dt.Columns.Count; i++)
            {
    
    
                worksheet.Cells[1, i + 1].Value = dt.Columns[i].ColumnName;
            }

            // 将DataTable的数据写入工作表中
            for (int i = 0; i < dt.Rows.Count; i++)
            {
    
    
                for (int j = 0; j < dt.Columns.Count; j++)
                {
    
    
                    worksheet.Cells[i + 2, j + 1].Value = dt.Rows[i][j];
                }
            }

            // 保存Excel文件
            FileInfo excelFile = new FileInfo(filePath);
            excelPackage.SaveAs(excelFile);
        }

Method 3. Use the NPOI library

Add citation:

using System;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

Dump the DataTable as an Excel file:

        public static void Convert(DataTable dt, string filePath)
        {
    
    
            // 创建一个新的Excel工作簿
            IWorkbook workbook = new XSSFWorkbook();

            // 创建一个新的工作表并命名为“Sheet1”
            ISheet worksheet = workbook.CreateSheet("Sheet1");

            // 将DataTable的列名写入工作表中
            IRow headerRow = worksheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
    
    
                ICell cell = headerRow.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
            }

            // 将DataTable的数据写入工作表中
            for (int i = 0; i < dt.Rows.Count; i++)
            {
    
    
                IRow dataRow = worksheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
    
    
                    ICell cell = dataRow.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }

            // 保存Excel文件
            using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
    
    
                workbook.Write(fileStream);
            }
        }

DataTable to CSV

Add citation:

using System;
using System.Data;
using System.IO;

Dump the DataTable as a CSV file:

        public static void Convert(DataTable dataTable, string filePath)
        {
    
    
            // 创建一个写入器
            using (StreamWriter writer = new StreamWriter(filePath))
            {
    
    
                // 写入表头
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
    
    
                    writer.Write(dataTable.Columns[i].ColumnName);
                    if (i < dataTable.Columns.Count - 1)
                    {
    
    
                        writer.Write(",");
                    }
                }
                writer.Write(writer.NewLine);

                // 写入表数据
                foreach (DataRow row in dataTable.Rows)
                {
    
    
                    for (int i = 0; i < dataTable.Columns.Count; i++)
                    {
    
    
                        writer.Write(row[i].ToString());
                        if (i < dataTable.Columns.Count - 1)
                        {
    
    
                            writer.Write(",");
                        }
                    }
                    writer.Write(writer.NewLine);
                }
            }
        }

DataTable to TXT

Add citation:

using System;
using System.Data;
using System.IO;

Dump the DataTable as a TXT file:

        public static void Convert(DataTable dataTable, string filePath, string delimiter = "\t")
        {
    
    
            // 创建一个写入器
            using (StreamWriter writer = new StreamWriter(filePath))
            {
    
    
                // 写入表头
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
    
    
                    writer.Write(dataTable.Columns[i].ColumnName);
                    if (i < dataTable.Columns.Count - 1)
                    {
    
    
                        writer.Write(delimiter);
                    }
                }
                writer.Write(writer.NewLine);

                // 写入表数据
                foreach (DataRow row in dataTable.Rows)
                {
    
    
                    for (int i = 0; i < dataTable.Columns.Count; i++)
                    {
    
    
                        writer.Write(row[i].ToString());
                        if (i < dataTable.Columns.Count - 1)
                        {
    
    
                            writer.Write(delimiter);
                        }
                    }
                    writer.Write(writer.NewLine);
                }
            }
        }

DataGridView export data to JSON, XML format

Please refer to the article: "C# | DataGridView data transfer to Json, XML format"


conclusion

I hope this article can help you and make you more familiar with file export and data format conversion techniques in the C# programming language.

If you have any questions or suggestions, please leave a comment below.

Guess you like

Origin blog.csdn.net/lgj123xj/article/details/130072215