locked
download a excel file RRS feed

  • Question

  • User-1471881183 posted

    hello mates,

    in .net 5 core web application wtih EF Core; my aim is to create a excel file from controller based on List<> and its achieved by using interop

    the next step is to download the same excel file so, below is my code. here is my doubt, I have assigned the file path into a ViewBag then I dont know how dowload the file(FYI this file path is not in Model) so, may I know how to download the file;

    public ActionResult Test(temp1Template temp1)
            {
                if (temp1.Date != null)
                {
                    CommonFunctions.CommonFunction objCommon = new CommonFunctions.CommonFunction();
    
                    string strDate = objCommon.DateFormat(temp1.Date);
                    string fileName = Guid.NewGuid().ToString() + ".xls";
    
                    string location = Directory.GetCurrentDirectory() + (@"\Docs\Xls\");
    
                    if (!System.IO.Directory.Exists(location))
                    {
                        System.IO.Directory.CreateDirectory(location);
                    }
                    string customExcelSavingPath = location + fileName;
                    _logger.LogInformation("File Path " + customExcelSavingPath);
                    List<temp1Template> list = GetData(customExcelSavingPath, strDate);
    ViewBag.FileDownload = customExcelSavingPath; return View("Test", list); } return View("Test"); }

    Wednesday, April 21, 2021 12:05 PM

Answers

  • User475983607 posted

    View i already pass html file then a List<>(return View("Test", list);) so, I wan to download the file without affecting existing data flow from controller to view. could you please guide me on this?

    For the second time, you must create a link and provide the file path in the view.  

    <a href="/docs/myexcelfile.xlsx">My Excel File</a>

    Or from a model

    <a href="@Model.ExcelFilePath">My Excel File</a>

    This concept is covered in any beginning level MVC tutorial.  Unfortunately, you have not provided all the relevant code so it is difficult to understand what problem you are having.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 21, 2021 1:04 PM
  • User1686398519 posted

    Hi winseealn, 

    You should return a relative path.For example:

    Controller

            public IActionResult UploadFile(IFormFile uploadfile)
            {
                string fileName = Guid.NewGuid().ToString() + ".xls";
                string location = Directory.GetCurrentDirectory() + (@"\Docs\Xls\");
                if (!System.IO.Directory.Exists(location))
                {
                    System.IO.Directory.CreateDirectory(location);
                }
                string filePath = Path.Combine(@"\Docs\Xls\", fileName);
                string customExcelSavingPath = location + fileName;
                using (FileStream stream = new FileStream(customExcelSavingPath, FileMode.Create))
                {
                    uploadfile.CopyTo(stream);
                }
                ViewBag.FileDownload = filePath;
                return View();
            }

    View

    @if (ViewBag.FileDownload != null)
    {
        <a href="@ViewBag.FileDownload">testfile</a>
    }

    Startup

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
                ... ...
                app.UseAuthorization();
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider = new PhysicalFileProvider(
                         Path.Combine(env.ContentRootPath, "Docs")),
                    RequestPath = "/Docs"
                });
                app.UseSession();
                ... ...
    }

    Result

     

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 22, 2021 6:20 AM

All replies

  • User475983607 posted

    First, office interop is not designed or intended for use on a Web Server.  See the Office interop documentation.  Use a library like EPPLUS or OpenXml.

    Secondly, downloading a file is very simple.  Just take advantage of the File() method of the Controller.  See the official docs; https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.file?view=aspnet-mvc-5.2

    Example.

    [HttpGet]
    public async Task<IActionResult> Get(string fileName)
    {
        string filePath = System.IO.Path.Combine(_webHostEnvironment.WebRootPath, "docs", fileName);
        byte[] buffer = await System.IO.File.ReadAllBytesAsync(filePath);
        return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "MyExcelFile.xlsx");
    }

    Perhaps you wish to render a link to the file???  If so then just render a link where the path points to the Excel file saved in the wwwroot folder.  If the file is stored outside the wwwroot then you'll need to configure a file provider.  Read the docs; https://docs.microsoft.com/en-us/aspnet/core/fundamentals/file-providers?view=aspnetcore-5.0

    Wednesday, April 21, 2021 12:32 PM
  • User-1471881183 posted

    @mgebhard thank you for your response.

    my doubt is about how to make the file downloadable since, in the return View i already pass html file then a List<>(return View("Test", list);) so, I wan to download the file without affecting existing data flow from controller to view. could you please guide me on this?

    Wednesday, April 21, 2021 12:47 PM
  • User475983607 posted

    View i already pass html file then a List<>(return View("Test", list);) so, I wan to download the file without affecting existing data flow from controller to view. could you please guide me on this?

    For the second time, you must create a link and provide the file path in the view.  

    <a href="/docs/myexcelfile.xlsx">My Excel File</a>

    Or from a model

    <a href="@Model.ExcelFilePath">My Excel File</a>

    This concept is covered in any beginning level MVC tutorial.  Unfortunately, you have not provided all the relevant code so it is difficult to understand what problem you are having.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 21, 2021 1:04 PM
  • User1686398519 posted

    Hi winseealn, 

    You should return a relative path.For example:

    Controller

            public IActionResult UploadFile(IFormFile uploadfile)
            {
                string fileName = Guid.NewGuid().ToString() + ".xls";
                string location = Directory.GetCurrentDirectory() + (@"\Docs\Xls\");
                if (!System.IO.Directory.Exists(location))
                {
                    System.IO.Directory.CreateDirectory(location);
                }
                string filePath = Path.Combine(@"\Docs\Xls\", fileName);
                string customExcelSavingPath = location + fileName;
                using (FileStream stream = new FileStream(customExcelSavingPath, FileMode.Create))
                {
                    uploadfile.CopyTo(stream);
                }
                ViewBag.FileDownload = filePath;
                return View();
            }

    View

    @if (ViewBag.FileDownload != null)
    {
        <a href="@ViewBag.FileDownload">testfile</a>
    }

    Startup

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
                ... ...
                app.UseAuthorization();
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider = new PhysicalFileProvider(
                         Path.Combine(env.ContentRootPath, "Docs")),
                    RequestPath = "/Docs"
                });
                app.UseSession();
                ... ...
    }

    Result

     

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 22, 2021 6:20 AM
  • User753101303 posted

    Hi,

    You don't do both at the same time. It seems you aee confusing returninng a view showing a download link and actually returning the file. If the file is not directly exposed on your web site you can have another action that returns an action result that iunherits from https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fileresult?view=aspnetcore-5.0 to send back the file content to the browser. Using https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fileresult.filedownloadname?view=aspnetcore-5.0#Microsoft_AspNetCore_Mvc_FileResult_FileDownloadName will use https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#examples to trigger the download dialog.

    Edit: and if exposed directly your https://www.w3schools.com/tags/att_a_download.asp link will just point directly to the file. It's basically the same ie the link is returning the file content and the browser knows that the file just be downloaded rather than replacing the current view.

    Thursday, April 22, 2021 7:06 AM