首页 > 代码库 > 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 { }
        }
    }