Return Dowload Excel via MVC Controller

Asked

Viewed 1,118 times

5

I have a method that generates an excel file and writes it in a directory, but then I take the path of the directory and I need to download the excel file, but nothing occurs, no error. Can anyone help in what I’m failing?

[HttpGet]
    public FileResult ObterDadosClientesBDO(ParametrosListaCliente filtro)
    {
        var jsonResult = Json(InstanceResolverFor<IServicoListaClientesBDO>.Instance.ObterDadosClientesBDO(filtro).ToArray(), JsonRequestBehavior.AllowGet);
        jsonResult.MaxJsonLength = int.MaxValue;

        string nomeRelatorio = string.Format("{0}{1}.xlsx","NOMERELATORIO", DateTime.Now.ToString("ddMMyyyyhhmmss"));
        string caminhoRelatorio = GerarRelatorioExcel(jsonResult, nomeRelatorio);


        return File(caminhoRelatorio, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", nomeRelatorio);
    }
  • Have you tried switching to the second File parameter for "application/vnd.ms-excel"?

  • I’ve done it, but on the same thing, nothing happens, no error on the console too.

  • Play the return of File in a Filecontentresult, check what it returns. If you want to put inside a Try/catch that will probably return the error. After that edit the result in your question.

1 answer

2


In his return File no error is occurring probably because the return of the object is being null, is still a problem, but there is a Exception Handling in this case and no exception is played as the application can handle the error without affecting the rest of the operation of the application.

The caminhoRelatorio must be pointing out the wrong path of the file, to get around this you can do a treatment as in the example below:

[HttpGet]
public FileResult ObterDadosClientesBDO(ParametrosListaCliente filtro)
{
    var jsonResult = Json(InstanceResolverFor<IServicoListaClientesBDO>.Instance.ObterDadosClientesBDO(filtro).ToArray(), JsonRequestBehavior.AllowGet);
    jsonResult.MaxJsonLength = int.MaxValue;

    string nomeRelatorio = string.Format("{0}{1}.xlsx","NOMERELATORIO", DateTime.Now.ToString("ddMMyyyyhhmmss"));
    string caminhoRelatorio = GerarRelatorioExcel(jsonResult, nomeRelatorio);

    var arquivo = File(caminhoRelatorio, "application/vnd.ms-excel", nomeRelatorio);

    if(arquivo == null)
    {
        //se for nulo apresenta uma mensagem de aviso antes do return
        return arquivo;
    }
    else
    {
        //Se não apenas retorne o arquivo
        return arquivo;
    }
}

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.