将标题添加到我的 csv 文件中

Posted

技术标签:

【中文标题】将标题添加到我的 csv 文件中【英文标题】:prepend headers to my csv file 【发布时间】:2017-04-05 04:38:15 【问题描述】:

我想将标题添加到我的 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 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..");

       if (!File.Exists(comboBox5.Text))
        

            string rxHeader = "Code" + "," + "Description" + "," + "NDC" + "," + "Supplier Code"
               + "," + "Supplier Description" + "," + "Pack Size" + "," + "UOM" + Environment.NewLine;


            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();
        

    

我真的很想尝试在没有 SteamWriter 的情况下实现它,我哪里错了?

private void button6_Click_2(object sender, EventArgs e)
    

        int count_row = dataGridView1.RowCount;
        int count_cell = dataGridView1.Rows[0].Cells.Count;
        string path = "C:\\Users\\jdavis\\Desktop\\" + comboBox5.Text + ".csv";
        string rxHeader = "Code" + "," + "Description" + "," + "NDC" + "," + "Supplier Code"
        + "," + "Supplier Description" + "," + "Pack Size" + "," + "UOM";


        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";

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

【问题讨论】:

关于 WriteAllText 的 MSDN :如果目标文件已经存在,则将其覆盖。 所以上面的代码总是重写所有标题或其他内容。 其实没有。我导出到文件并将其附加到现有数据中,因此您实际上对此有误。隐藏的文本框是 @Steve 的解决方法 @RezaAghaei 如果我按照我在原始问题中的更新尝试中的建议检查它是否存在,该怎么办 史蒂夫没有错,他实际上是直接从文档中复制/粘贴的。 WriteAllText 覆盖文件。当然,您正在通过使用一串文本框来保留附加文本来解决这个问题,但最后,当您调用该方法时,您正在替换整个文件,而不是附加到它。 显然你并没有意识到这一点,否则你就不会写这个“实际上不,它没有”来回应史蒂夫的评论。在解决这个问题方面,我可能会提供一些东西,但必须指出这一点,因为当那个人实际上完全正确时,你公然告诉某人是错的。 【参考方案1】:

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

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

【讨论】:

【参考方案2】:

这是我建议的解决方案。 我的建议是先检查文件是否存在,然后再决定是否需要写header。

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:\***QuestionsAndAnswers\40726017\File1.txt";
        string filePath2 = @"M:\***QuestionsAndAnswers\40726017\File2.txt";
        string filePath3 = @"M:\***QuestionsAndAnswers\40726017\File3.txt";
        string filePath4 = @"M:\***QuestionsAndAnswers\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!
        
    

【讨论】:

我真的很想在没有 SteamWriter 的情况下这样做,你能看看我更新的代码,看看哪里出错了吗?【参考方案3】:

只需用这个 sn-p 编辑我的代码即可得到答案:

 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();
    

【讨论】:

【参考方案4】:
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() + ",";

    

进入textBox8的属性面板即可。文本并用逗号添加列标题,并将 textbox8 可见性设置为隐藏。

【讨论】:

以上是关于将标题添加到我的 csv 文件中的主要内容,如果未能解决你的问题,请参考以下文章

如何在 iOS 7 中将 CSV 文件关联到我的应用程序

转换为镶木地板的 csv 文件将“e0”添加到值的末尾

无法将新帐户信息写入 csv 文件

如何使用 Google Sheets API V4 导入 CSV 文件

我的 .csv 文件应该在哪里使用 XAMPP 导入到我的 MYSQL 数据库中?

如何将 TXT 文件作为资源添加到我的 EXE 文件中?