最近有一个项目使用以前的ashx,不能使用FileResult,只有通过response返回拼接好的字符串。但是通过查阅资料拼接的字符串总是提示文件格式不匹配,虽然能正常打开,但是体验很不好,在此总结一下我的解决方法:
直接下载excel会提示格式不相符,稍微修改,下载成csv的就没问题了
- 后台:
/// <summary>
/// DataTable导出到Excel
/// </summary>
/// <param name="dt">DataTable类型的数据源</param>
/// <param name="FileType">文件类型</param>
/// <param name="FileName">文件名</param>
public void CreateExcel(HttpContext context, List<PB_SITE_BASIC> siteList, string FileName)
{
//分割符
string split = ",";
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.Clear();
Response.Charset = "UTF-8";
Response.Buffer = true;
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".csv\"");
Response.ContentType = "application/ms-excel";
string colHeaders = string.Empty;
string ls_item = string.Empty;
int i = 0;
int cl = siteList.Count;
//添加表头
ls_item += "站点编号" + split;
ls_item += "站点名称" + split;
ls_item += "车桩总数" + split;
ls_item += "基站地址" + split;
ls_item += "所属区域" + split;
ls_item += "站点地址" + split;
ls_item += "站点纬度" + split;
ls_item += "站点经度" + split;
ls_item = ls_item.Substring(0, ls_item.Length - 1) + "\n";
foreach (var site in siteList)
{
ls_item += site.SID.ToString() + split;
ls_item += site.NAME.ToString() + split;
ls_item += site.CAPACITY.ToString() + split;
ls_item += site.BASESTATION_ID.ToString() + split;
ls_item += site.REGION_ID.ToString() + split;
ls_item += site.ADDRESS.ToString() + split;
ls_item += site.LAT.ToString() + split;
ls_item += site.LNG.ToString() + split;
ls_item += "\n";
Response.Output.Write(ls_item);
ls_item = string.Empty;
}
Response.Output.Flush();
Response.End();
}
- 前台
//导出
$("#btExport").click(function () {
window.location = "ExportSiteBasic.ashx";
});