如题,把Gridview中的数据全部按行列导入到了Excel文件中,存在服务器上的该Excel文件正确。在用FileStream传送到客户端服务器的时候,显示“文件下载”,单击“保存”,在“另存为”对话框,选择保存地点,“确定”时,弹出窗口:
      “无法复制  文件:无法读源文件或磁盘”。
    我是借鉴一个开源考试系统中的源代码,除了读GridView处不同外,其他没变,而且在VS中,考试系统的下载为Excel是正常的。而我中午在我的网站中实验时,也是可以正常从浏览器下载Excel的,但是不知什么原因,下午就不行了,显示上面的错误,我又打开考试系统,该功能一直正常。
    我仔细检查我的代码和考试系统的代码,甚至把考试系统的直接粘贴过来,仅修改读取GridView的部分,仍然是存到服务器端的Excel正常,但从客户端下载时还是该错误。会是什么原因呢?
    在逐句调试过程中,发现提示错误对话框出在红字代码中:但是这段代码在考试系统中是一字没动的。Buffer中的字节流是正确的。
       //打开要下载的文件,并把该文件存放在FileStream中
        System.IO.FileStream Reader = System.IO.File.OpenRead(NewFileName);
        //文件传送的剩余字节数:初始值为文件的总大小
        long Length = Reader.Length;        Response.Buffer = false;
        Response.AddHeader("Connection", "Keep-Alive");
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode("学生成绩.xls"));
        Response.AddHeader("Content-Length", Length.ToString());        byte[] Buffer = new Byte[10000]; //存放欲发送数据的缓冲区
        int ByteToRead; //每次实际读取的字节数        while (Length > 0)
        {
            //剩余字节数不为零,继续传送
            if (Response.IsClientConnected)
            {
                //客户端浏览器还打开着,继续传送
                ByteToRead = Reader.Read(Buffer, 0, 10000); //往缓冲区读入数据
                Response.OutputStream.Write(Buffer, 0, ByteToRead); //把缓冲区的数据写入客户端浏览器
                Response.Flush(); //立即写入客户端
                Length -= ByteToRead; //剩余字节数减少
            }
            else
            {
                //客户端浏览器已经断开,阻止继续循环
                Length = -1;
            }
        }        //关闭该文件
        Reader.Close();

解决方案 »

  1.   

    Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName.Substring(FileName.LastIndexOf('/') + 1), System.Text.Encoding.GetEncoding("utf-8"))); 
    Response.ContentType = "application/octet-stream"; 
    Response.WriteFile(""); 
    Response.End();protected void Btn_Click(object sender, EventArgs e)
    {
    string style = @"<style> .text { mso-number-format:\@; } </script> "; 
    Response.ClearContent();
    Response.AddHeader("content-disposition", "attachment; filename=ExcelFile.xls");
    Response.ContentType = "application/excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    gv.RenderControl(htw);
    Response.Write(style); 
    Response.Write(sw.ToString());
    Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
      

  2.   

    我发现给我回答问题的wuyq11是个大牛啊!