Set Download Location With EPPlus

南楼画角 提交于 2019-12-02 20:26:27

问题


I was following This tutorial on EPPlus, but I am left scratching my head on how to set the downloads location to the logged in users "Downloads" folder? I know for me the location would be this, but is their a way to assign it w/o knowing the logged on persons account info?

C:\Users\laptop\Downloads

And here is my syntax:

 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());
}

回答1:


You are mixing apples and oranges. File.WriteAllBytes is part of System.IO and it intended to manipulate files "locally", e.g. the app writes to the local hard drive.

Asp.net is web so you need to do something like this:

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();
}

(Take from my post here: Open ExcelPackage Object with Excel application without saving it on local file path)

This will fire the download through the browser which will use what default settings the use has and get you what your looking for.



来源:https://stackoverflow.com/questions/31123352/set-download-location-with-epplus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!