我正在使用ClosedXML和数据表导出Excel,并且效果很好。我的问题是编码混乱了我的语言,例如:“æ”显示为
æ
我已经尝试了很多类似添加的操作:
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.Unicode;
或使用编码将流更改为字节:
MemoryStream memoryStream = new MemoryStream();
wb.SaveAs(memoryStream);
memoryStream.Position = 0;
byte[] bytes = memoryStream.ToArray();
char[] chars = Encoding.UTF8.GetChars(bytes);
Response.BinaryWrite(UTF8Encoding.UTF8.GetBytes(chars));
但是我一直以丢失的编码或损坏的文件结尾。我不知道还能尝试什么,所以我希望您能将我引向正确的道路?
我的代码:
using (XLWorkbook wb = new XLWorkbook())
{
var dt = new DataTable("Bookinglist");
foreach (TableCell cell in gv.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in gv.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
}
}
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.Unicode;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=BookingList.xlsx");
using (MemoryStream ms = new MemoryStream())
{
wb.SaveAs(ms);
ms.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}