Exporting data to CSV from Controller

后端 未结 1 397
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 10:14

I\'m using the CsvHelper library in an ASP.NET MVC project to export data to CSV, and am finding that the exported data is either cut off, or in the case of smaller lists, n

相关标签:
1条回答
  • 2021-01-07 10:50

    The reason is because you're not flushing the data in the writer to the stream. The writer will periodically flush itself when it's full, but you need to make sure to do it at the end.

    Option 1:

    using (var memoryStream = new MemoryStream())
    using (var streamWriter = new StreamWriter(memoryStream))
    using (var csvWriter = new CsvWriter(streamWriter))
    {
        csvWriter.WriteRecords(data);
        streamWriter.Flush();
        memoryStream.Position = 0;
        return File(memoryStream, "text/csv", filename);
    }
    

    Option 2:

    using (var memoryStream = new MemoryStream())
    {
        using (var streamWriter = new StreamWriter(memoryStream))
        using (var csvWriter = new CsvWriter(streamWriter))
        {
            csvWriter.WriteRecords(data);
        } // The stream gets flushed here.
        memoryStream.Position = 0;
        return File(memoryStream, "text/csv", filename);
    }
    
    0 讨论(0)
提交回复
热议问题