C# 将DataGridView中显示的数据导出到CSV

创建类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Export
{
    public class ExportDgvToCSV
    {
        #region
        public void ExportToCsv(string fileName, DataGridView dgv)
        {
            Stopwatch sp = null;            
            StreamWriter sw = null;

            //判断datagridview中内容是否为空
            if (dgv.Rows.Count == 0)
            {
                MessageBox.Show("DataGridView中内容为空,请先导入数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //保存文件     
            string saveFileName = "";
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.DefaultExt = "cxv";
            saveFileDialog.Filter = "CSV文件(*.csv)|*.csv";
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.Title = "CSV文件保存路径";
            saveFileDialog.FileName = fileName;
                    
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                //**程序开始计时**//
                sp = new Stopwatch();
                sp.Start();

                try
                {
                    saveFileName = saveFileDialog.FileName;                    

                    //指定编码和缓冲区
                    int size = 1024;
                    int sizeCnt = (int)Math.Ceiling((Double)dgv.RowCount / (Double)2000);
                    sw = new StreamWriter(saveFileName, false, Encoding.Default, size * sizeCnt);
                    
                    //添加列名   
                    string head = "";
                    for (int columnNum = 0; columnNum < dgv.Columns.Count; columnNum++)
                    {                       
                        if (dgv.Columns[columnNum].Visible == true)
                        {
                            head += dgv.Columns[columnNum].HeaderText + ",";
                        }
                    }
                    sw.WriteLine(head);

                    //写入内容
                    for (int rowNum = 0; rowNum < dgv.RowCount; rowNum++)
                    {                  
                        if (dgv.Rows[rowNum].Visible == true)
                        {
                            string Tem = "";
                            for (int columnNum1 = 0; columnNum1 < dgv.ColumnCount; columnNum1++)
                            {
                                if (dgv.Columns[columnNum1].Visible == true)
                                {
                                    if (dgv.Rows[rowNum].Cells[columnNum1].Value != null)
                                    {
                                        string TemString = dgv.Rows[rowNum].Cells[columnNum1].Value.ToString().Trim().Replace(",", ".").Replace("\r\n", ".").Replace("\r", ".").Replace("\n", ".");
                                        Tem += TemString;
                                        Tem += ",";
                                    }
                                    else
                                    {
                                        string TemString = "";
                                        Tem += TemString;
                                        Tem += ",";
                                    }
                                }
                            }
                            sw.WriteLine(Tem);
                        }
                    }
                    sw.Flush();
                    sw.Close();

                    //**程序结束计时**//
                    sp.Stop();
                    double totalTime = sp.ElapsedMilliseconds / 1000.0;

                    MessageBox.Show(fileName + " 导出成功\n耗时" + totalTime + "s", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "导出错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }                
            }
        }
        #endregion       
    }
}


调用

private void btnExportToCsv_Click(object sender, EventArgs e)
{
	ExportDgvToCSV export = new ExportDgvToCSV();
	export.ExportToCsv("", dgv);
}

原文链接:https://blog.csdn.net/xggbest/article/details/104229171

你可能感兴趣的:(笔记,csv)