记一次服务器生成Excel在客户端下载的案例

今天加盟部校长说做一个用户数据收集并导出Excel文件的小网页,主要便于查看客户信息,前期一切顺利,就在生成Excel和下载的时候出现了问题,收集了一些资料,有人说用NPOI插件,这个可行,我在网上收集了资料,没有使用插件做了一个简单的Excel生成器,话不多少代码如下:

首先在服务类中

   //导出Excel
        /// <summary>
        /// DataTable导出到Excel
        /// </summary>
        /// <param name="table">DataTable类型的数据源</param>
        /// <param name="file">需要导出的文件路径</param>
        public void dataTableToCsv(DataTable table, string file)
        {
            string title = "";
            FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
            for (int i = 0; i < table.Columns.Count; i++)
            {
                title += table.Columns[i].ColumnName + "\t"; //栏位:自动跳到下一单元格
            }
            title = title.Substring(0, title.Length - 1) + "\n";
            sw.Write(title);
            foreach (DataRow row in table.Rows)
            {
                string line = "";
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    line += row[i].ToString().Trim() + "\t"; //内容:自动跳到下一单元格
                }
                line = line.Substring(0, line.Length - 1) + "\n";
                sw.Write(line);
            }
            sw.Close();
            fs.Close();
        }

我是用一般处理程序做业务层,其代码如下所示:

 string UserName = context.Request["name"].ToString();
                string UserType = context.Request["type"].ToString();

                DataSet ds = cs.Get_JQ_Info(UserName, UserType);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    //D:\WebSoft\WebSoft10\SoftWeb\Services\down\2018-09-08 170615.xls
                    string path = context.Server.MapPath("../down/" + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls");
                    cs.dataTableToCsv(ds.Tables["JG"], path); //调用函数
                    string[] arr = path.Split('\\');
                    string pp = "";
                    for (int i = 0; i < arr.Length; i++)
                    {
                        if (arr[i].Contains("2018")) {
                            pp = arr[i].ToString();
                        }
                    }
                    



                    this.downloadfile(context, "../down/"+pp);
                  
               
                    
                    
                }
                else
                {

                    context.Response.Write("Error");
                }

    //文件下载
    public void downloadfile(HttpContext context, string s_fileName)
    {
        string path = s_fileName;
        System.IO.FileInfo file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(path));
       
        context.Response.Clear();
        context.Response.Charset = "UTF-8";
        context.Response.ContentEncoding = System.Text.Encoding.UTF8;
        context.Response.AddHeader("Content-Type", "application/octet-stream");
        // 添加头信息,为"文件下载/另存为"对话框指定默认文件名,设定编码为UTF8,防止中文文件名出现乱码
        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8));
        // 添加头信息,指定文件大小,让浏览器能够显示下载进度
        context.Response.AddHeader("Content-Length", file.Length.ToString());
        //// 指定返回的是一个不能被客户端读取的流,必须被下载
        context.Response.ContentType = "application/ms-excel";
        // 把文件流发送到客户端
        context.Response.WriteFile(file.FullName);
        // 停止页面的执行
        context.Response.End();
    }

特别说明!!!!!!!!!!!!

前端调用千万别用AJAX,无论如何调都不会出现弹框的,这时请使用<a href=""></a>的方式进行下载。

由于浏览器网页关闭了,引用地址无法给出,若是引用了某位大神的代码或者内容,请谅解,再次抱歉。

猜你喜欢

转载自www.cnblogs.com/CS521/p/9609893.html