问题
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