Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get all the data to CSV from memorystream?

Below is my method to export data to 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

If the number of records is less than 100.Then no issue. But when the data is 100 or 150+ , last 15-20records are not written to the csv file.

Suppose if the number of records is 175, then I get in csv some around 163. If the number of records is 150 then I get in csv arounf 131 & so on.

What could be the causing this ? How should I handle this?

like image 980
Kgn-web Avatar asked Oct 29 '25 23:10

Kgn-web


1 Answers

A number small updates in my public method fixed my issue.

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

}

Hope this helps :)

like image 80
Kgn-web Avatar answered Oct 31 '25 16:10

Kgn-web



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!