• 点滴积累【C#】---C#实现下载word


    效果:

    思路:

    简单的有两种方式下载,一种是流下载,一种是WriteFile下载。以下是使用WriteFile下载。

    代码:

     1 protected void LinkButton1_Click(object sender, EventArgs e)
     2         {
     3             try
     4             {
     5                 //WriteFile实现下载(word)
     6                 string fileName = "qingpingguo.docx";//客户端保存的文件名
     7                 string filePath = Server.MapPath("~\excel\" + tb1.Text);//路径
     8 
     9                 FileInfo fileInfo = new FileInfo(filePath);
    10                 Response.Clear();
    11                 Response.ClearContent();
    12                 Response.ClearHeaders();
    13                 Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
    14                 Response.AddHeader("Content-Length", fileInfo.Length.ToString());
    15                 Response.AddHeader("Content-Transfer-Encoding", "binary");
    16                 Response.ContentType = "application/octet-stream";
    17                 Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
    18                 Response.WriteFile(fileInfo.FullName);
    19                 Response.Flush();
    20                 Response.End();
    21             }
    22             catch (Exception ex)
    23             {
    24                 Response.Write(ex.Message);
    25             }
    26 
    27             /*************以下为流方式下载****************/
    28             //string fileName = "aaa.txt";//客户端保存的文件名
    29             //string filePath = Server.MapPath("DownLoad/aaa.txt");//路径
    30 
    31             ////以字符流的形式下载文件
    32             //FileStream fs = new FileStream(filePath, FileMode.Open);
    33             //byte[] bytes = new byte[(int)fs.Length];
    34             //fs.Read(bytes, 0, bytes.Length);
    35             //fs.Close();
    36             //Response.ContentType = "application/octet-stream";
    37             ////通知浏览器下载文件而不是打开
    38             //Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
    39             //Response.BinaryWrite(bytes);
    40             //Response.Flush();
    41             //Response.End();
    42 
    43         }
  • 相关阅读:
    python re模块
    python
    python
    Django学习手册
    Django学习手册
    前端
    前端
    Django学习手册
    前端
    Database学习
  • 原文地址:https://www.cnblogs.com/xinchun/p/3488247.html
Copyright © 2020-2023  润新知