1

I am trying to generate a csv with UTF8 encoding with c#, using ExcelPackage (). Excel is identifying the file as .xlsx and not UTF8. My code:

using (ExcelPackage package = new ExcelPackage())
{
    ExcelWorksheet ws = package.Workbook.Worksheets.Add("myName");
    int y = 1;
    foreach (IDictionary<string, string> elemento in losDatos)
    {
        ws.Cells["A" + y].Value = "+ Disposición de contacto";
        ws.Cells["B" + y].Value = "Llamada detallada";
        ...
        ...
        ws.Cells["AL" + y].Value = "1";
        y++;
    }

    Response.Clear();
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
    Response.BinaryWrite(package.GetAsByteArray());
    Response.End();
}

I have tried some changes, only in the Response piece, and now the csv recognizes me, but the characters are strangers:

    Response.Clear();
    Response.ContentType = "application/csv";
    Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
    Response.BinaryWrite(Encoding.UTF8.GetPreamble());
    Response.BinaryWrite(package.GetAsByteArray());
    Response.End();
gabi13
  • 101
  • 8

1 Answers1

0

Replace

Response.ContentType = "application/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
Response.BinaryWrite(Encoding.UTF8.GetPreamble());

with

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".xlsx");

and you are done.

If you want a CSV, use a different package but then do consider adding charset to the Content-Type header. If Open XML is not your thing, then OpenDocument Spreadsheet (.odt, LibreOffice) would be equally better than CSV.

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72