C# 将DataGridView中的数据导出为.CSV文件

话不多说,直接上代码了

public void DataGridViewToExcel(DataGridView dgv)
{
    SaveFileDialog dlg = new SaveFileDialog();
    dlg.Filter = "Execl files (*.csv)|*.csv";
    dlg.FilterIndex = 0;
    dlg.RestoreDirectory = true;
    dlg.CreatePrompt = true;
    dlg.Title = "保存为csv文件";
    if (dlg.ShowDialog() == DialogResult.OK)
     {
         Stream myStream;
         myStream = dlg.OpenFile();
         StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
         string columnTitle = "";
         try
         {
             //写入列标题    
             for (int i = 0; i < dgv.ColumnCount; i++)
             {
                if (i > 0)
                {
                    columnTitle += ",";
                }
                columnTitle += dgv.Columns[i].HeaderText;
             }

             sw.WriteLine(columnTitle);

             //写入列内容    
             for (int j = 0; j < dgv.Rows.Count; j++)
             {
                 string columnValue = "";
                 for (int k = 0; k < dgv.Columns.Count; k++)
                 {
                     if (k > 0)
                     {
                         columnValue += ",";
                     }
                     if (dgv.Rows[j].Cells[k].Value == null)
                         columnValue += "";
                     else if (dgv.Rows[j].Cells[k].Value.ToString().Contains(","))
                     {
                         columnValue += "\"" + dgv.Rows[j].Cells[k].Value.ToString().Trim() + "\"";
                     }
                     else
                     {
                         columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim() + "\t";
                     }
                }
                sw.WriteLine(columnValue);
           }
           sw.Close();
           myStream.Close();                 
           MassageBox.Show("导出表格成功!");
      }
      catch (Exception e)
      {
          MessageBox.Show("导出表格失败!");               
      }
      finally
      {
         sw.Close();
         myStream.Close();
      }
      else          
         MessageBox.Show("取消导出表格操作!"); 
}

注意事项:

将数据导出为.csv格式的文件后,在进行数据计算的时候会比较麻烦。若是要对导出后的数据进行计算,建议导出为Excel形式。

你可能感兴趣的:(c#)