prepend headers to my csv file

前端 未结 4 437
长发绾君心
长发绾君心 2021-01-29 07:18

I want to prepend headers to my CSV File as to let the data reflect the headings. How would I go about this without having to add it each time writing to the file? Meaning I onl

4条回答
  •  深忆病人
    2021-01-29 08:12

    Here is the short version that will even properly handle values that contain , and ":

    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
    

提交回复
热议问题