我试图在ASP中输出一个excel文件作为附件。NET,很难用土耳其语编码。以下代码是我所做的;我将我尝试过的行作为评论留下:
var collection = Data.Get<Students>()
.Where(t => t.Year == activeYear)
.OrderBy(t => t.Name);
var total = collection.Count();
DataTable dt = collection.ToDataTable();
dt.Columns.Remove("Id");
string htmlCode = "<table>";
//add header row
htmlCode += "<tr>";
htmlCode += "<td>#</td>";
for (int i = 0; i < dt.Columns.Count; i++)
{
htmlCode += "<td>" + dt.Columns[i].ColumnName + "</td>";
}
htmlCode += "</tr>";
//add rows
for (int i = 0; i < dt.Rows.Count; i++)
{
htmlCode += "<tr>";
htmlCode += "<td>" + (dt.Rows.Count-i+1).ToString() + "</td>";
for (int j = 0; j < dt.Columns.Count; j++)
{
htmlCode += "<td>" + dt.Rows[i][j].ToString() + "</td>";
}
htmlCode += "</tr>";
}
htmlCode += "</table>";
////////////////////////////////////
// Encoding part begins here
////////////////////////////////////
var output = htmlCode;
Encoding encoding = new UTF8Encoding(true); //Encoding.UTF8; //new UTF8Encoding(true);
var utf8bytes = encoding.GetBytes(output);
utf8bytes = Encoding.UTF8.GetPreamble().Concat(utf8bytes).ToArray();
byte[] bytes = new UTF8Encoding(true).GetBytes(output);
//MemoryStream stream = new MemoryStream(utf8bytes);
MemoryStream stream = new MemoryStream(bytes);
StreamReader reader = new StreamReader(stream);
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
string attachment = "attachment; filename=" + Utils.Security.RemoveDiacritics(currentLesson + "-" + activeYear) + ".xls";
Response.AddHeader("content-disposition", attachment);
//Response.ContentType = "application/octet-stream";
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = new UTF8Encoding(true); //Encoding.GetEncoding("windows-1254"); // Encoding.UTF8;
Response.Output.Write(reader.ReadToEnd());
Response.Flush();
Response.End();
如果我使用新的UTF8Encoding(true)或false,输出总是不带签名的UTF8。如果我在Notepad2中打开文件,并将其编码为带有签名的UTF8,则名称将正确显示。
这是下载的Excel文件,Excel中的名称不正确:
这是Notepad2中修改后的Excel文件,其名称在Excel中显示正确:
为了更正名称,我使用Notepad2打开下载的xls文件,并使用Signature将编码从UTF8更改为UTF8。现在,我如何在服务器端做到这一点?
更新:
HEX编辑器屏幕截图显示了文件之间的差异,只在xls平面文本文件的开头添加了3个字节: