您好我使用下面的代码将数据表导出到Excel文件
string attachment = "attachment; filename=Data.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dtDataForExport.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dtDataForExport.Rows)
{
tab = "";
for (i = 0; i < dtDataForExport.Columns.Count; i++)
{
string content = dr[i].ToString();
content.Replace(System.Environment.NewLine, " ");
Response.Write(tab + content);
tab = "\t";
}
Response.Write("\n");
}
Response.End();
正如您所看到的,我已尝试替换System.Environment.NewLine
,但我仍然遇到导致Excel文档出现问题的行,是否有人有任何建议可以摆脱这些?
答案 0 :(得分:4)
Strings是不可变的,这意味着你无法修改它们,这就是为什么它不起作用:
content.Replace(System.Environment.NewLine, " ");
您没有将字符串重新分配给您的变量:
content = content.Replace(System.Environment.NewLine, " ");