使用 EPPlus 设置下载位置

Set Download Location With EPPlus

我正在关注 EPPlus 上的 This 教程,但我对如何将下载位置设置为登录用户 "Downloads" 文件夹感到困惑?我知道我的位置是这个,但是他们是否可以通过 w/o 知道已登录人员的帐户信息来分配它?

C:\Users\laptop\Downloads

这是我的语法:

 string location = "C:\";
 string filename = "EPPlusTest.xlsx";
 using (ExcelPackage objExcelPackage = new ExcelPackage())
 {
    ExcelWorksheet objWorksheet = objExcelPackage.Workbook.Worksheets.Add("Sheet 1");
    objWorksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
    using (ExcelRange objRange = objWorksheet.Cells["A1:XFD1"])
    {
      objRange.Style.Font.Bold = true;
      objRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
      objRange.Style.VerticalAlignment = ExcelVerticalAlignment.Center;                
    }
    using (ExcelRange dataRange = objWorksheet.Cells["A2:XFD20"])
    {
      dataRange.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
      dataRange.Style.VerticalAlignment = ExcelVerticalAlignment.Bottom;
    }
  FileStream objFileStrm = File.Create(filename);
  objFileStrm.Close();
  File.WriteAllBytes(location + filename, objExcelPackage.GetAsByteArray());
}

您正在混合苹果和橙子。 File.WriteAllBytes 是 System.IO 的一部分,它旨在操纵文件 "locally",例如应用程序写入本地硬盘。

Asp.net 是网络所以你需要做这样的事情:

using (ExcelPackage pck = new ExcelPackage())
{
    var ws = pck.Workbook.Worksheets.Add("Demo");
    ws.Cells[1, 2].Value = "Excel Test";

    var fileBytes = pck.GetAsByteArray();
    Response.Clear();

    Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
    Response.AppendHeader("Content-Disposition",
        String.Format("attachment; filename=\"{0}\"; size={1}; creation-date={2}; modification-date={2}; read-date={2}"
            , "temp.xlsx"
            , fileBytes.Length
            , DateTime.Now.ToString("R"))
        );
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    Response.BinaryWrite(fileBytes);
    Response.End();
}

(取自我的 post 此处:Open ExcelPackage Object with Excel application without saving it on local file path

这将通过浏览器启动下载,浏览器将使用用户的默认设置并为您提供所需内容。