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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值