我正在编码一个SQL客户端,您可以在其中将DataGridView导出到CSV(Excel)。 问题是我在名为“ ID”的单元中有多个条目,就像ID的21倍是4倍,但电话号码不同。
这是我目前的代码:
private void ButtonDataGridInCSVExport(object sender, EventArgs e)
{
if (dataGridViewResult.Rows.Count == 0)
{
return;
}
StringBuilder stringBuilder = new StringBuilder();
string csvheader = "";
for (int i = 0; i < dataGridViewResult.Columns.Count; i++)
{
csvheader += dataGridViewResult.Columns[i].Name + ";";
}
stringBuilder.Append(csvheader + Environment.NewLine);
foreach (DataGridViewRow dataGridViewRow in dataGridViewResult.Rows)
{
if (!dataGridViewRow.IsNewRow)
{
for (int c = 0; c < dataGridViewRow.Cells.Count; c++)
{
stringBuilder.Append(dataGridViewRow.Cells[c].FormattedValue + ";");
}
stringBuilder.Append(Environment.NewLine);
}
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(saveFileDialog.FileName, false, Encoding.UTF8))
{
sw.WriteLine(stringBuilder.ToString());
MessageBox.Show("CSV file saved.");
}
}
}
有人知道如何做到这一点吗?
这是现在的样子: How it looks like now
它应该是这样的: How it should look like