我找到了将数据表导出为excel的代码,但我无法弄清楚如何让控制器返回结果。
有什么建议吗?这是代码
dt = city.GetAllCity();//your datatable
string attachment = "attachment; filename=city.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
答案 0 :(得分:0)
您可以返回FileStreamResult:
public ActionResult DownloadCities()
{
dt = city.GetAllCity();//your datatable
string attachment = "attachment; filename=city.xls";
var writer = new StreamWriter(new MemoryStream());
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
writer.Write(tab + dc.ColumnName);
tab = "\t";
}
writer.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
writer.Write(tab + dr[i]);
tab = "\t";
}
writer.Write("\n");
}
return File(writer.BaseStream, "application/vnd.ms-excel", "city.xls");
}