首页 > 代码库 > FileUtils 文件下载 文件导出
FileUtils 文件下载 文件导出
public class FileUtils { /// <summary> /// 文件下载 /// </summary> /// <param name="page">页面参数</param> /// <param name="filePath">文件源路径</param> /// <param name="saveFileName">文件命名</param> public static void FileDownload(System.Web.UI.Page page, string filePath, string saveFileName) { try { if (!string.IsNullOrEmpty(filePath)) { string fileExtension = filePath.Substring(filePath.LastIndexOf(‘.‘));//后缀 //saveFileName = filePath.Substring(filePath.LastIndexOf(@"\"));//文件名 page.Response.Clear(); page.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(saveFileName))); page.Response.Charset = "utf-8"; page.Response.ContentEncoding = System.Text.Encoding.Default; page.Response.WriteFile(filePath); //page.Response.Flush(); page.Response.End(); //HttpContext.Current.ApplicationInstance.CompleteRequest(); } } catch { } } /// <summary> /// 文件导出 /// </summary> /// <param name="page">对象页面</param> /// <param name="filePath">文件保存服务器路径</param> /// <param name="dt">数据源</param> /// <param name="exportFileName">导出后的文件名称</param> public static void ExportFile(System.Web.UI.Page page, string filePath, DataTable dt, string exportFileName) { try { if (File.Exists(filePath)) { File.Delete(filePath); } StreamWriter sw = new StreamWriter(new FileStream(filePath, FileMode.CreateNew), System.Text.Encoding.GetEncoding("GB2312")); sw.Write(exportFileName); sw.WriteLine(); int i = 0; for (i = 0; i <= dt.Columns.Count - 1; i++) { sw.Write(dt.Columns[i].ColumnName); sw.Write(‘\t‘); } sw.WriteLine(); foreach (DataRow dr in dt.Rows) { for (i = 0; i <= dt.Columns.Count - 1; i++) { sw.Write(dr[i].ToString()); sw.Write(‘\t‘); } sw.WriteLine(); } sw.Close(); FileDownload(page, filePath, exportFileName); } catch { } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。