C# 將EXCEL表格轉化為二進制字符串,通過文件流讓前端下載


/// <summary>
/// EXCEL表格轉化為二進制字符串導出
/// </summary>
/// <param name="path">文件路徑</param>
public void DownLoadModuleFile(string path)
{
  // 若已知單獨文件地址可直接傳入地址
  var path = HttpContext.Current.Server.MapPath(path);

  // 將文件讀取成二進制流
  FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
  BinaryReader r = new BinaryReader(fs);
  byte[] buf = r.ReadBytes((int)fs.Length);
  fs.Dispose();
  
  //文件名
  var fileName = $"test.xlsx";
  //流方式下載文件
  HttpContext.Current.Response.ContentType = "application/octet-stream";
  //通知瀏覽器下載文件而不是打開
  HttpContext.Current.Response.AddHeader("Content-Disposition",$"attachment; filename={HttpUtility.UrlEncode(fileName)}");
  HttpContext.Current.Response.BinaryWrite(buf);
  HttpContext.Current.Response.Flush();
  HttpContext.Current.Response.End();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM