简体   繁体   中英

How do I write CSV file with header using FileHelpers?

I am using FileHelpers to write DataTable content into CSV file.

Because of huge number of records in DataTable I chose to dump the result set as it is in DataTable into CSV file like below

CommonEngine.DataTableToCSV(dt, filename)

And the CSV has sucessfully written with 2 million records having the size of 150MB.

But I wanted to add the filed header at first line of this CSV file.

Is there a way FileHelper will allow to write the header using CommonEngine.DataTableToCSV?

在调用WriteFile之前,必须使用engine.HeaderText = engine.GetFileHeader()

Looking at the source code, it looks like there is no way of setting the header line. However, it is easy to copy the code and write your own replacement. Something like this:

public static void DataTableToCsv(DataTable dt, string filename, CsvOptions options, string headerLine)
{
    using (StreamWriter writer = new StreamWriter(filename, false, options.Encoding, 102400))
    {
        // output header
        writer.Write(headerLine);
        writer.Write(StringHelper.NewLine);

        foreach (DataRow row in dt.Rows)
        {
            object[] itemArray = row.ItemArray;
            for (int i = 0; i < itemArray.Length; i++)
            {
                if (i > 0)
                {
                    writer.Write(options.Delimiter);
                }
                writer.Write(options.ValueToString(itemArray[i]));
            }
            writer.Write(StringHelper.NewLine);
        }
        writer.Close();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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