繁体   English   中英

如何编写字符串以格式化行数据以另存为CSV文件?

[英]How can I write a string to format row data to save as a CSV file?

我目前有一个使用StreamReader访问CSV文件并将值存储在数据网格中的程序,但是在保存此数据时,它正在为数据行的每个列值打印新行。

该程序当前将csv文件打印为:

headerText,headerText,headerText,headerText
第1栏,第2栏,第1栏,第2栏,第3栏,第1栏,第2栏,第3栏,第4栏

我需要打印的是:

headerText,headerText,headerText,headerText
第1栏,第2栏,第3栏,第4栏

string CsvFpath = "C:/StockFile/stockfiletest.csv";

try
{
    StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
    string columnHeaderText = "";
    int countColumn = stockGridView.ColumnCount - 1;

    if (countColumn >= 0)
    {
        columnHeaderText = stockGridView.Columns[0].HeaderText;
    }

    for (int i = 1; i <= countColumn; i++)
    {
        columnHeaderText = columnHeaderText + ',' + stockGridView.Columns[i].HeaderText;
    }

    csvFileWriter.WriteLine(columnHeaderText);

    foreach (DataGridViewRow dataRowObject in stockGridView.Rows)
    {
        if (!dataRowObject.IsNewRow)
        {
            string dataFromGrid = "{0} += {1} += {2} += {3}";
            dataFromGrid = dataRowObject.Cells[0].Value.ToString();

            for (int i = 1; i <= countColumn; i++)
            {
                dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
                csvFileWriter.Write(dataFromGrid);
            }
            csvFileWriter.WriteLine();
        }
    }

    csvFileWriter.Dispose();

    MessageBox.Show("Saved stockfile.csv");
}
catch (Exception exceptionObject)
{
    MessageBox.Show(exceptionObject.ToString());
}

谁能告诉我我的String格式在做什么以及如何实现所需的文件输出?

您的问题在这里:

for (int i = 1; i <= countColumn; i++)
{
  dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
      csvFileWriter.Write(dataFromGrid);
}

您每次都添加到字符串中。.在任何时候都不会清除它。 因此,在第1行的第一列上,您获得的“,col1” col2是“,col1,col2” ..但您每次也要写出来。

有一个CSV编写器类,但是您可以做您正在做的事情,但是,只需将写操作移到循环外,然后将其重置即可。 然而..

for (int i = 1; i <= countColumn; i++)
{
      if (i>1) csvFileWriter.Write(",");
      csvFileWriter.Write(dataRowObject.Cells[i].Value.ToString());
}

一开始会阻止您获得多余的“,”并按原样编写

作为另一个答案提到的,问题是,你在循环里面写入文件,以便处理每一列,而不是在循环 ,当你收集了所有该行的列信息。

您可以执行此操作的另一种方法是使用string.JoinSystem.Linq来更简洁地连接每行的列值。

还要注意,我们可以将csvFileWriter包装在using块中,以便在块执行完成时自动将其关闭并csvFileWriter

using (var csvFileWriter = new StreamWriter(CsvFpath, false))
{
    // Write all the column headers, joined with a ','
    csvFileWriter.WriteLine(string.Join(",",
        stockGridView.Columns.Cast<DataGridViewColumn>().Select(col => col.HeaderText)));

    // Grab all the rows that aren't new and, for each one, join the cells with a ','
    foreach (var row in stockGridView.Rows.Cast<DataGridViewRow>()
        .Where(row => !row.IsNewRow))
    {
        csvFileWriter.WriteLine(string.Join(",",
            row.Cells.Cast<DataGridViewCell>().Select(cell => cell.Value.ToString())));
    }
}

另一件事:不用编写自己的csv解析器,而是可以使用现有的工具来编写csv文件,例如CsvHelper ,它可以处理其他类型的可能导致问题的边缘情况,例如其中包含逗号的值。

暂无
暂无

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

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