简体   繁体   English

C#将DataGridView导出到CSV文件

[英]C# Exporting DataGridView to CSV file

As you can see from the pictures i have attached below i am having some trouble with converting this to a valid csv file. 从下面的图片中可以看到,将其转换为有效的csv文件时遇到了一些麻烦。 I am nearly there but cant quite figure out the last bit i need. 我快到了,但我想不起来我需要的最后一点。 I need to bring the column headers into the textbox and i also need to remove the ',' at the end of each line. 我需要将列标题带入文本框,并且还需要删除每行末尾的“,”。 BTW i am converting the top DGV. 顺便说一句,我正在转换顶级DGV。

在此处输入图片说明

在此处输入图片说明

here is my code - 这是我的代码-

private void btnSave_Click(object sender, EventArgs e)
    {
        int countRow = dgvCsv1.RowCount;
        int cellCount = dgvCsv1.Rows[0].Cells.Count;


        for (int rowIndex = 0; rowIndex <= countRow -1; rowIndex++)
        {
            for (int cellIndex = 0; cellIndex <= cellCount - 1; cellIndex++)
            {
                textBoxExport.Text = textBoxExport.Text + dgvCsv1.Rows[rowIndex].Cells[cellIndex].Value.ToString() + ",";
            }
            textBoxExport.Text = textBoxExport.Text + "\r\n";
        }

        System.IO.File.WriteAllText(lblFilePath.Text, textBoxExport.Text);
    }

Any help greatly appreciated. 任何帮助,不胜感激。

This has already been solved here . 这已经在这里解决 The LINQ solution does exactly what you want. LINQ解决方案完全可以满足您的需求。

var sb = new StringBuilder();

var headers = dgvCsv1.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));

foreach (DataGridViewRow row in dgvCsv1.Rows)
{
    var cells = row.Cells.Cast<DataGridViewCell>();
    sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}

So the final code would look like: 因此,最终代码如下所示:

private void btnSave_Click(object sender, EventArgs e)
    {
        var sb = new StringBuilder();

        var headers = dgvCsv1.Columns.Cast<DataGridViewColumn>();
        sb.AppendLine(string.Join(",", headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));

        foreach (DataGridViewRow row in dgvCsv1.Rows)
        {
            var cells = row.Cells.Cast<DataGridViewCell>();
            sb.AppendLine(string.Join(",", cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
        }
        textBoxExport.Text = sb.ToString();

        System.IO.File.WriteAllText(lblFilePath.Text, textBoxExport.Text);
    }
  1. Remove last delimiter (comma) 删除最后一个定界符(逗号)

You already have the number of columns ColumnCount, therefore, while looping through the columns, a simple check is needed to see if the currentColumn is “less than” the ColumnCount -1. 您已经具有ColumnCount,的列数ColumnCount,因此,在遍历各列时,需要进行简单的检查以查看currentColumn是否“小于” ColumnCount -1。 If the currentColumn IS less than ColumnCount -1, then you need to add the “comma” , . 如果currentColumn小于ColumnCount -1,那么你需要添加“逗号” , If currentColumn is NOT “less than” ColumnCount , then this can mean only one thing… this is the last column and instead of adding the comma you want to add a new line. 如果currentColumn不小于ColumnCount ,那么这仅意味着一件事……这是最后一列,您无需添加逗号就可以添加新行。

if (currentCol < ColumnCount - 1) {
  textBoxExport.Text += ",";
}
else {
  textBoxExport.Text += Environment.NewLine;
}
  1. Column Headers in CSV file CSV文件中的列标题

This will need to be separate from looping through the rows. 这需要与遍历行分开。 Before looping through the rows, loop through the columns of the grid and get each columns Name property. 在遍历行之前,遍历网格的列并获取每个列的Name属性。 This would be the first line in the CSV file. 这将是CSV文件中的第一行。 You can use the same strategy as above to avoid the last comma. 您可以使用与上述相同的策略来避免最后一个逗号。

for (int currentCol = 0; currentCol < ColumnCount; currentCol++) {
  textBoxExport.Text += dgvCsv1.Columns[currentCol].Name;
  if (currentCol < ColumnCount - 1) {
    textBoxExport.Text += ",";
  }
  else {
    textBoxExport.Text += Environment.NewLine;
  }
}

Lastly, it is unclear why you are using a TextBox to store the CSV string. 最后,不清楚为什么要使用TextBox存储CSV字符串。 I recommend using a StringBuilder. 我建议使用StringBuilder. Below is an example of what is described above. 以下是上述内容的示例。

private void btnSave_Click(object sender, EventArgs e) {
  StringBuilder sb = new StringBuilder();
  int RowCount = dgvCsv1.RowCount;
  int ColumnCount = dgvCsv1.ColumnCount;

  // get column headers
  for (int currentCol = 0; currentCol < ColumnCount; currentCol++) {
    sb.Append(dgvCsv1.Columns[currentCol].Name);
    if (currentCol < ColumnCount - 1) {
      sb.Append(",");
    }
    else {
      sb.AppendLine();
    }
  }

  // get the rows data
  for (int currentRow = 0; currentRow < RowCount; currentRow++) {
    if (!dgvCsv1.Rows[currentRow].IsNewRow) {
      for (int currentCol = 0; currentCol < ColumnCount; currentCol++) {
        if (dgvCsv1.Rows[currentRow].Cells[currentCol].Value != null) {
          sb.Append(dgvCsv1.Rows[currentRow].Cells[currentCol].Value.ToString());
        }
        if (currentCol < ColumnCount - 1) {
          sb.Append(",");
        }
        else {
          sb.AppendLine();
        }
      }
    }
  }
  textBoxExport.Text = sb.ToString();
  System.IO.File.WriteAllText(@"D:\Test\DGV_CSV_EXPORT.csv", sb.ToString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM