1

I have the following controller action used to export a csv file

public ActionResult ExportExcel(int projectId)
        {
            var risks = new RiskRepository().GetRisksByProjectId(projectId);
            var commaDelimmeted =
                    risks.Select(
                        r => r.RiskDescription + "," + r.RiskTypeId.ToString() + "," + r.Likelihood.ToString() + "," + r.Impact + "," + r.Action + "," + r.ActionBy + ",")
                        .ToList();

            string data = commaDelimmeted.Aggregate(string.Empty, (current, line) => current + line + Environment.NewLine);

            Response.ClearContent();
            Response.Buffer = true;
            // set the header
            var aliasName = "someFile.csv";
            Response.AddHeader("content-disposition", "attachment; filename=" + aliasName);
            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.ContentEncoding = Encoding.UTF8;
            Response.Output.Write(data);
            Response.Flush();
            Response.End();

            return File(Response.OutputStream, "application/csv");
        }

The output csv file do not show right to left langauge characters properly, so I've set response content encoding header the problem still exists.

Any thoughts?

Edit : Looking at Darin's solution in this post didn't fix my problem , the output shows System.Byte[] in the csv output file.

0

3 Answers 3

2

Based on this post, it turns out the encoding preamble must be appended to the csv data like this :

using (var sw = System.IO.File.Create(csvPath))
            {
                var preamble = Encoding.UTF8.GetPreamble();
                sw.Write(preamble, 0, preamble.Length);
                var databytes = Encoding.UTF8.GetBytes(data);
                sw.Write(databytes, 0, data.Length);
            }

and this did the trick.

Sign up to request clarification or add additional context in comments.

Comments

0
 Have you tried setting the encoding in a meta tag in the HTML?

 <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
   Excel won't see the response headers, so it won't know what the Response.Encoding is. The meta tag allows it to find out.

1 Comment

do you mean that I have to append this to my data string?
0

Unless you absolutely need it to be a CSV file I'd recommend converting it to use ClosedML (available on NuGet) to generate a proper XLSX file - you can then use the GetMimeMapping function and return a FileStreamResult.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.