在 C# 中将 DataGridView 数据导出为 CSV

        在此代码示例中,我们将学习如何使用 C# 代码将 DataGridView 数据导出到 CSV 文件并将其保存在文件夹中。
 
        在这个程序中,首先,我们必须连接到数据库并从中获取数据。然后,我们将在数据网格视图中显示该数据,如下图所示。

让我们转到页面加载事件,获取员工数据,并绑定数据 GridView。

private void FrmExport_Load(object sender, EventArgs e)  
{  
    SqlConnection sqlCon;  
    string conString = null;  
    string sqlQuery = null;  
  
    conString = "Data Source=.;Initial Catalog=DemoTest;Integrated Security=SSPI;";  
    sqlCon = new SqlConnection(conString);  
    sqlCon.Open();  
    sqlQuery = "SELECT * FROM tblEmployee";  
    SqlDataAdapter dscmd = new SqlDataAdapter(sqlQuery, sqlCon);  
    DataTable dtData = new DataTable();  
    dscmd.Fill(dtData);  
    dataGridView1.DataSource = dtData;  

然后,在按钮单击事件处理程序上,编写以下代码。

private void btnCsv_Click(object sender, EventArgs e)  
{  
    if (dataGridView1.Rows.Count > 0)  
    {  
        SaveFileDialog sfd = new SaveFileDialog();  
        sfd.Filter = "CSV (*.csv)|*.csv";  
        sfd.FileName = "Output.csv";  
        bool fileError = false;  
        if (sfd.ShowDialog() == DialogResult.OK)  
        {  
            if (File.Exists(sfd.FileName))  
            {  
                try  
                {  
                    File.Delete(sfd.FileName);  
                }  
                catch (IOException ex)  
                {  
                    fileError = true;  
                    MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);  
                }  
            }  
            if (!fileError)  
            {  
                try  
                {  
                    int columnCount = dataGridView1.Columns.Count;  
                    string columnNames = "";  
                    string[] outputCsv = new string[dataGridView1.Rows.Count + 1];  
                    for (int i = 0; i < columnCount; i++)  
                    {  
                        columnNames += dataGridView1.Columns[i].HeaderText.ToString() + ",";  
                    }  
                    outputCsv[0] += columnNames;  
                              
                    for (int i = 1; (i - 1) < dataGridView1.Rows.Count; i++)  
                    {  
                        for (int j = 0; j < columnCount; j++)  
                        {  
                            outputCsv[i] += dataGridView1.Rows[i - 1].Cells[j].Value.ToString() + ",";  
                        }  
                    }  
  
                    File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);  
                    MessageBox.Show("Data Exported Successfully !!!", "Info");  
                }  
                catch(Exception ex)  
                {  
                    MessageBox.Show("Error :" + ex.Message);  
                }  
            }  
        }  
    }  
    else  
    {  
        MessageBox.Show("No Record To Export !!!", "Info");  
    }  

        现在,运行应用程序。点击“导出为 CSV”按钮时,它会询问文件保存位置。输入文件名,然后点击“确定”。它会生成一个 CSV 文件。

希望这段代码能帮助到所有读者。祝您编码愉快!

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值