C# 一些代码小结--datGirdView 保存到csv文件

 if (dataGridView1.Rows.Count == 0)
 {
     MessageBox.Show("No data available!", "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Information);
     return;
 }
else
{
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
    saveFileDialog.FilterIndex = 0;
    saveFileDialog.RestoreDirectory = true;
    saveFileDialog.CreatePrompt = true;
    saveFileDialog.FileName = null;
    saveFileDialog.Title = "Save path of the file to be exported";
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        Stream myStream = saveFileDialog.OpenFile();
        StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
        string strLine = "";
        try
        {
            //Write in the headers of the columns.
            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            {
                if (i > 0)
                    strLine += ",";
                strLine += dataGridView1.Columns[i].HeaderText;
            }
            strLine.Remove(strLine.Length - 1);
            sw.WriteLine(strLine);
            strLine = "";
            //Write in the content of the columns.
            for (int j = 0; j < dataGridView1.Rows.Count; j++)
            {
                strLine = "";
                for (int k = 0; k < dataGridView1.Columns.Count; k++)
                {
                    if (k > 0)
                        strLine += ",";
                    if (dataGridView1.Rows[j].Cells[k].Value == null)
                        strLine += "";
                    else
                    {
                        string m = dataGridView1.Rows[j].Cells[k].Value.ToString().Trim();
                        strLine += m.Replace(",", ",");
                    }
                }
                strLine.Remove(strLine.Length - 1);
                sw.WriteLine(strLine);
                //Update the Progess Bar.
                // toolStripProgressBar1.Value = 100 * (j + 1) / dataGridView1.Rows.Count;
            }
            sw.Close();
            myStream.Close();
            MessageBox.Show("Data has been exported to:" + saveFileDialog.FileName.ToString(), "Exporting Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
            // toolStripProgressBar1.Value = 0;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Exporting Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值