I am a new developer and currently learning dotnet core angular technologies.
I have a dotnet core project that allows me to download a SQL table as an excel file using EPPlus.Core
library. When I test the code below, it works fine. I am able to get the excel file from my Downloads folder. However, when I publish it to the IIS, the code works fine but no files in the Downloads folder.
When I debug this, I realized that the frontend (in my case, it's angular) does not have access to my Downloads folder even though I explicitly declared in my controller. Here is my controller code that allows me to export as excel file.
[HttpGet]
[Route("ExportParticipants")]
public string ExportParticipants()
{
string rootFolder = System.Convert.ToString(
Microsoft.Win32.Registry.GetValue(
@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
,"{374DE290-123F-4565-9164-39C4925E467B}"
,String.Empty));
var list = DateTime.Now.ToString("yyyy-MM-dd-HH-mmss");
string fileName = @"Export_Participants_" + list + "_.xlsx";
FileInfo file = new FileInfo(Path.Combine(rootFolder, fileName));
using (ExcelPackage package = new ExcelPackage(file))
{
IList<Participant> participantList = context.Participants.ToList();
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Participants");
int totalRows = participantList.Count();
worksheet.Cells[1, 1].Value = "#";
worksheet.Cells[1, 2].Value = "FirstName";
worksheet.Cells[1, 3].Value = "Last Name";
int i = 0;
for (int row = 2; row <= totalRows + 1; row++)
{
worksheet.Cells[row, 1].Value = i+1;
worksheet.Cells[row, 2].Value = participantList[i].FirstName;
worksheet.Cells[row, 3].Value = participantList[i].LastName;
i++;
}
package.Save();
}
return " Participant list has been exported successfully";
}
The code above works fine when I test it with postman. However, When I publish it, it doesn't work. I receive no error. But I found out that the issue is rootFolder
. So I tried the following code:
string rootFolder = Environment.GetEnvironmentVariable("USERPROFILE") + @"\" + "Downloads";
And I even tried Ray Koopa's article in Code Project but I got the nothing in the downloads folder.
How can I place this exported excel file to the current user's Downloads folder? Please note that I use windows.
Or should I do this in the frontend? Should I look for a npm package and use it on the frontend? If so, which package you recommend it for me?
Thank you all for the help!
This will download the excel file inside the server's downloads folder. Instead of dealing with MemoryStream
, I will use a frontend library. Since I have the list of participants in a JASON array form, DataTables library is a good one to go. It's not only to export excel, we can do pdf, print preview as well as a copy to the clipboard. I don't work for them. I have no affiliations with them. But I found it very useful in my case.