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

时间:2016-11-21 17:30:24

标签: c# winforms csv

我想在我的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();
            }
        }
    }

4 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

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

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!
        }
    }

答案 2 :(得分:0)

只需使用此代码段编辑我的代码即可得到答案:

 SELECT MIN(VhrNum) FROM table_name where EmptyOrNot=1;

答案 3 :(得分:0)

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的属性pannel即可。使用逗号添加文本并添加列标题,并将textbox8可见性设置为隐藏。