问题描述
如何将数据网格正确导出到CSV?为什么行在不同的列中?
How can I export my datagrid to CSV correctly? Why are the Rows in different columns?
ExportToCsv函数返回:
ExportToCsv function return:
"SR#;请求的8D报告;状态(ASSIST);正在研发; BTQ编号;优先级;目标日期;实施日期;状态(BTQ)"
"SR #;8D Report Requested;Status (ASSIST);In R&D;BTQ NUMBER;Priority;Target Date;Implementation Date;Status (BTQ)"
行:错误!
"1-3271406718;是;是; BTQ00153254; 6-增强功能; 22.02.2014; 09.09.2014;已完成;正在等待"
"1-3271406718;yes;yes;BTQ00153254;6 - Enhancement;22.02.2014;09.09.2014 ;COMPLETED;Eng. wait"
应该如何:
"SR#;请求的8D报告;状态(ASSIST);正在研发; BTQ编号;优先级;目标日期;实施日期;状态(BTQ)"
"SR #;8D Report Requested;Status (ASSIST);In R&D;BTQ NUMBER;Priority;Target Date;Implementation Date;Status (BTQ)"
行:
"1-3271406718;是;工程等待;是; BTQ00153254; 6-增强功能; 22.02.2014; 09.09.2014;已完成"
"1-3271406718;yes;Eng. wait;yes;BTQ00153254;6 - Enhancement;22.02.2014;09.09.2014 ;COMPLETED"
这是我的代码:
string CsvFpath = saveDLG.FileName;
StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
string columnHeaderText = "";
int countColumn = dgvView.Columns.Count - 1;
if (countColumn >= 0)
{
columnHeaderText = (dgvView.Columns[0].Header).ToString();
}
//Writing column headers
for (int i = 1; i <= countColumn; i++)
{
columnHeaderText = columnHeaderText + ';' + (dgvView.Columns[i].Header).ToString();
}
csvFileWriter.WriteLine(columnHeaderText);
// Writing values row by row
for (int i = 0; i <= dgvView.Items.Count - 2; i++)
{
string dataFromGrid = "";
for (int j = 0; j <= dgvView.Columns.Count - 1; j++)
{
if (j == 0)
{
dataFromGrid = ((DataRowView)dgvView.Items[i]).Row.ItemArray[j].ToString();
}
else
{
dataFromGrid = dataFromGrid + ';' + ((DataRowView)dgvView.Items[i]).Row.ItemArray[j].ToString();
}
}
csvFileWriter.WriteLine(dataFromGrid);
}
csvFileWriter.Flush();
csvFileWriter.Close();
推荐答案
尝试使用Linq.它更简单易读:
Try it with Linq. It's simpler and easy to read:
public string DataGridToCSV(string delimiter = ";")
{
var sb = new StringBuilder();
var headers = myDataGridView.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join(delimiter, headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));
foreach (DataGridViewRow row in myDataGridView.Rows)
{
var cells = row.Cells.Cast<DataGridViewCell>();
sb.AppendLine(string.Join(delimiter, cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}
return sb.ToString();
}
只需将字符串另存为*.csv
文件即可.
Just save the String as *.csv
File and you're done.
这篇关于从DataGrid导出CSV-错误的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!