C# 在我的csv文件前添加标题

C# 在我的csv文件前添加标题,c#,winforms,csv,C#,Winforms,Csv,我想在我的CSV文件中预先添加标题,以便让数据反映标题。如果每次写入文件时都不必添加它,我将如何执行此操作?这意味着我只希望在每次导出时添加一次标题。当我导出到相同的文件名时,它不应该创建相同标题的副本。下面是我写入文件的代码: private void button6_Click_2(object sender, EventArgs e) { int count_row = dataGridView1.RowCount; int count_cell

我想在我的CSV文件中预先添加标题,以便让数据反映标题。如果每次写入文件时都不必添加它,我将如何执行此操作?这意味着我只希望在每次导出时添加一次标题。当我导出到相同的文件名时,它不应该创建相同标题的副本。下面是我写入文件的代码:

 private void button6_Click_2(object sender, EventArgs e)
    {

        int count_row = dataGridView1.RowCount;
        int count_cell = dataGridView1.Rows[0].Cells.Count;

        MessageBox.Show("Please wait while " +comboBox5.Text+ " table is being exported..");
        for (int row_index = 0; row_index <= count_row - 2; row_index++)
        {

            for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++)
            {
                textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ",";

            }
            textBox8.Text = textBox8.Text + "\r\n";
        }
        System.IO.File.WriteAllText("C:\\Users\\jdavis\\Desktop\\"+comboBox5.Text+".csv", textBox8.Text);
        MessageBox.Show("Export  of " +comboBox5.Text+ " table is complete!");
        textBox8.Clear();
    }
private void按钮6\u单击2(对象发送方,事件参数e)
{
int count_row=dataGridView1.RowCount;
int count_cell=dataGridView1.Rows[0].Cells.count;
MessageBox.Show(“正在导出“+comboBox5.Text+”表,请稍候…”);

对于(int row_index=0;row_index这是我建议的解决方案。 我的建议是首先检查文件是否存在,然后决定是否需要写入头文件

private void DoTheWork(int fileIDtoUpdate)
    {
        //this is just my representation of what probably already exist in your project
        string textInTheTextBox = "blah blah blah blah\nI love text\nI love code\nI love to Code\ndon't you just love to code!";
        string filePath1 = @"M:\StackOverflowQuestionsAndAnswers\40726017\File1.txt";
        string filePath2 = @"M:\StackOverflowQuestionsAndAnswers\40726017\File2.txt";
        string filePath3 = @"M:\StackOverflowQuestionsAndAnswers\40726017\File3.txt";
        string filePath4 = @"M:\StackOverflowQuestionsAndAnswers\40726017\File4.txt";
        string fileToWorkWith = string.Empty;
        //decide which file to work with
        switch (fileIDtoUpdate)
        {
            case 1:
                fileToWorkWith = filePath1;
                break;
            case 2:
                fileToWorkWith = filePath2;
                break;
            case 3:
                fileToWorkWith = filePath3;
                break;
            case 4:
                fileToWorkWith = filePath4;
                break;
            default:
                break;
        }
        //check if the file existed
        bool fileExisted = File.Exists(fileToWorkWith);
        using (StreamWriter sw = new StreamWriter(fileToWorkWith, true))
        {
            if (!fileExisted)
            {
                //if the file did not exist, then you need to put your header line!
                sw.WriteLine("Write your Header Line here");
            }
            sw.WriteLine(textInTheTextBox);//down here... who cares if the file existed or not, you need to append this text to it no matter what!
        }
    }

下面是一个简短的版本,它甚至可以正确处理包含
”的值:


只需使用以下代码片段编辑我的代码即可获得答案:

 if (!File.Exists(path))
    {
        System.IO.File.WriteAllText(path, rxHeader + textBox8.Text);
    }
    else
    {    
        System.IO.File.AppendAllText(path, textBox8.Text);
        MessageBox.Show("Export  of " + comboBox5.Text + " table is complete!");
        textBox8.Clear();
    }

用于(int row_index=0;row_index MSDN about writealText:如果目标文件已经存在,它将被覆盖。因此上面的代码总是重写所有标题或其他内容。实际上没有。我导出到文件并将其附加到现有数据中,因此您实际上对此有错误。隐藏的文本框是解决此问题的方法@Steve@RezaAghaei如果我检查它是否如我在原始问题中更新的尝试中所建议的那样存在该怎么办Steve没有错,他实际上是直接从文档中复制/粘贴了该文件。WriteAllText会覆盖该文件。当然,您可以通过使用一系列文本框来保留附加的文本来解决这个问题,但最后,当您调用该方法时,你正在替换整个文件,而不是附加到它。显然你没有意识到这一点,否则你就不会写这个“事实上没有”“对于Steve的评论,我可能会提供一些关于这个问题的解决方案,但必须指出这一点,因为你明目张胆地告诉某人是错的,而这个人实际上是完全正确的。我真的很想在没有SteamWriter的情况下这样做,你能看看我更新的代码,看看哪里出了错吗?”?
private void DoTheWork(int fileIDtoUpdate)
    {
        //this is just my representation of what probably already exist in your project
        string textInTheTextBox = "blah blah blah blah\nI love text\nI love code\nI love to Code\ndon't you just love to code!";
        string filePath1 = @"M:\StackOverflowQuestionsAndAnswers\40726017\File1.txt";
        string filePath2 = @"M:\StackOverflowQuestionsAndAnswers\40726017\File2.txt";
        string filePath3 = @"M:\StackOverflowQuestionsAndAnswers\40726017\File3.txt";
        string filePath4 = @"M:\StackOverflowQuestionsAndAnswers\40726017\File4.txt";
        string fileToWorkWith = string.Empty;
        //decide which file to work with
        switch (fileIDtoUpdate)
        {
            case 1:
                fileToWorkWith = filePath1;
                break;
            case 2:
                fileToWorkWith = filePath2;
                break;
            case 3:
                fileToWorkWith = filePath3;
                break;
            case 4:
                fileToWorkWith = filePath4;
                break;
            default:
                break;
        }
        //check if the file existed
        bool fileExisted = File.Exists(fileToWorkWith);
        using (StreamWriter sw = new StreamWriter(fileToWorkWith, true))
        {
            if (!fileExisted)
            {
                //if the file did not exist, then you need to put your header line!
                sw.WriteLine("Write your Header Line here");
            }
            sw.WriteLine(textInTheTextBox);//down here... who cares if the file existed or not, you need to append this text to it no matter what!
        }
    }
dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
dataGridView1.RowHeadersVisible = false;  // the row headers column is copied too if visible
dataGridView1.SelectAll();                // only the selected cells are used (the Windows Clipboard is not used)

DataObject dataObject = dataGridView1.GetClipboardContent();      // 4 Data Formats: Text,Csv,HTML Format,UnicodeText
File.WriteAllText("1.csv", dataObject.GetData("Csv") as string);  // DataFormats.CommaSeparatedValue = "Csv"

//string html = Encoding.ASCII.GetString((dataObject.GetData("HTML Format") as MemoryStream).ToArray()); // just the HTML Clipboard Format is in a MemoryStream
 if (!File.Exists(path))
    {
        System.IO.File.WriteAllText(path, rxHeader + textBox8.Text);
    }
    else
    {    
        System.IO.File.AppendAllText(path, textBox8.Text);
        MessageBox.Show("Export  of " + comboBox5.Text + " table is complete!");
        textBox8.Clear();
    }
for (int row_index = 0; row_index <= count_row - 2; row_index++)
{
    textBox8.Text = textBox8.Text + "\r\n";

    for (int cell_index = 1; cell_index <= count_cell - 1; cell_index++)
    {
        textBox8.Text = textBox8.Text + dataGridView1.Rows[row_index].Cells[cell_index].Value.ToString() + ",";

    }
}