如何从内存流中将所有数据转换为CSV?

时间:2016-12-12 09:32:18

标签: c# asp.net export-to-csv memorystream csvhelper

以下是将数据导出为CSV的方法。

public MemoryStream ExportToCsv(string jsonData, HttpResponseBase response, string fileName)
{
    using (MemoryStream stream = new MemoryStream())
    {
        StreamWriter writer = new StreamWriter(stream);
        try
        {
            String s = JsonToCsv(jsonData, ",");
            writer.Write(s);
            stream.Position = 0;
        }
        catch (Exception ex)
        {
            clsErrorHandling.WriteLog("CSVExport", "GenerateStreamFromString", ex.Message);
            throw;
        }
        finally
        {
            writer.Flush();
            writer.Close();
            response.Clear();
            response.Buffer = true;
            response.ContentType = "application/csv";
            response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + "");
            response.BinaryWrite(stream.ToArray());
        }

        return stream;
    }
}

#region Private CSV Block

private String JsonToCsv(string jsonData, string delimiter)
{
    try
    {
        using (StringWriter swObj = new StringWriter())
        {
            using (var csv = new CsvWriter(swObj))
            {
                csv.Configuration.SkipEmptyRecords = true;
                csv.Configuration.WillThrowOnMissingField = false;
                csv.Configuration.Delimiter = delimiter;

                using (var dt = jsonStringToTable(jsonData))
                {
                    foreach (DataColumn col in dt.Columns)
                    {
                        csv.WriteField(col.ColumnName);
                    }
                    csv.NextRecord();

                    foreach (DataRow row in dt.Rows)
                    {
                        for (var i = 0; i < dt.Columns.Count; i++)
                        {
                            csv.WriteField(row[i]);
                        }
                        csv.NextRecord();
                    }
                }

            }
            return swObj.ToString();
        }

    }
    catch (Exception ex)
    {
        clsErrorHandling.WriteLog("CSVExportHandler", "JsonToCsv", ex.Message);
        return null;
    }
}

private DataTable jsonStringToTable(string jsonContent)
{
    DataTable dt = JsonConvert.DeserializeObject<DataTable>(jsonContent);
    return dt;
}

#endregion

如果记录数小于100.那么没问题。但是当数据为100或150+时,最后15-20记录不会写入csv文件。

假设如果记录数是175,那么我在csv中得到一些大约163。 如果记录的数量是150,那么我进入csv arounf 131&amp;等等。

造成这种情况的原因是什么?我该怎么办呢?

1 个答案:

答案 0 :(得分:1)

我的public方法中的一些小更新解决了我的问题。

public MemoryStream ExportToCsv(string jsonData, HttpResponseBase response, string fileName)
{
       using (MemoryStream stream = new MemoryStream())
        {
            StreamWriter writer = new StreamWriter(stream);
            try
            {
                response.Clear();
                response.Buffer = true;
                response.ContentType = "application/csv";
                response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + "");
                String s = JsonToCsv(jsonData, ",");
                writer.Write(s);
                writer.Flush();

                stream.Position = 0;
                response.BinaryWrite(stream.ToArray());
            }
            catch (Exception ex)
            {

                throw;
            }
            finally
            {
                writer.Close();
            }
    return stream;
}

}

希望这有帮助:)