Download excel file

I created a file in excel, but now the user needs to download, How can I do ? follow my method:

    public PartialViewResult ExportarParticipantes(int idPeriodo)
    {

        Regex reg = new Regex("[/ :]");

        // Monta arquivo para análise
        string fileName = string.Format("{0}_{1}", reg.Replace(DateTime.Now.ToString(), "_").Replace("&", ""), Path.GetFileName("passagens.xls"));

        string caminhoArquivo = Path.Combine(Caminho, fileName);

        ExcelHelper excelHelper = new ExcelHelper(caminhoArquivo);

        // Obtém dados
        Dictionary<string, int> colunas = new Dictionary<string, int>();
        UploadPassagem lstParticipantePassagem = null;
        List<UploadPassagem> lista = new List<UploadPassagem>();

        GerenciaPassagemModel model = new GerenciaPassagemModel();

        Periodo periodo = new PeriodoService().ListarPorId(idPeriodo);

        model.Mensagem = ValidarPeriodo(periodo);
        model.ListaPassagens = new PassagemService().ListarPassagensPorPeriodo(idPeriodo, true);


        foreach (var item in model.ListaPassagens)
        {
            lstParticipantePassagem = new UploadPassagem(); 
            lstParticipantePassagem.PARTICIPANTE = item.Participante.NomeCompleto;
            lstParticipantePassagem.CPF = item.Participante.CPF;
            lstParticipantePassagem.PASSAGEM = item.Passagens.ToString();
            lstParticipantePassagem.CONCESSIONÁRIA = item.Participante.EstruturaAtual.EstruturaNome;
            lstParticipantePassagem.STATUS = item.Acao == true ? "Aprovado" : item.Acao == false ? "Recusado" : "Pendente";

            lista.Add(lstParticipantePassagem);

        }


        excelHelper.Export<UploadPassagem>(lista);

        return PartialView("_ListaParticipante", model);
    }
Author: Leonel Sanches da Silva, 2014-05-12

4 answers

Using EPPlus, here's how I'm doing it:

var memoryStream = package.GetAsByteArray();

return base.File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); //fileName é o nome do teu ficheiro
 2
Author: CesarMiguel, 2014-05-13 08:25:20

Let's say you created in a folder within your project Arquivo. Inside it has a file EXCEL(xls) with the name of Pasta 1.xls to which you want to download. Use in the return type method FileContentResult .

Code

public FileContentResult Excel()
{
      byte[] Excel = null;

      Excel = System.IO.File.ReadAllBytes(Server.MapPath("~/Arquivo/Pasta1.xls"));

      return new FileContentResult(Excel, "application/vnd.ms-excel");
}

In Your Code

public FileContentResult ExportarParticipantes(int idPeriodo)
{

    Regex reg = new Regex("[/ :]");

    // Monta arquivo para análise
    string fileName = string.Format("{0}_{1}", reg.Replace(DateTime.Now.ToString(), "_").Replace("&", ""), Path.GetFileName("passagens.xls"));

    string caminhoArquivo = Path.Combine(Caminho, fileName);

    ExcelHelper excelHelper = new ExcelHelper(caminhoArquivo);

    // Obtém dados
    Dictionary<string, int> colunas = new Dictionary<string, int>();
    UploadPassagem lstParticipantePassagem = null;
    List<UploadPassagem> lista = new List<UploadPassagem>();

    GerenciaPassagemModel model = new GerenciaPassagemModel();

    Periodo periodo = new PeriodoService().ListarPorId(idPeriodo);

    model.Mensagem = ValidarPeriodo(periodo);
    model.ListaPassagens = new PassagemService().ListarPassagensPorPeriodo(idPeriodo, true);


    foreach (var item in model.ListaPassagens)
    {
        lstParticipantePassagem = new UploadPassagem();
        lstParticipantePassagem.PARTICIPANTE = item.Participante.NomeCompleto;
        lstParticipantePassagem.CPF = item.Participante.CPF;
        lstParticipantePassagem.PASSAGEM = item.Passagens.ToString();
        lstParticipantePassagem.CONCESSIONÁRIA = item.Participante.EstruturaAtual.EstruturaNome;
        lstParticipantePassagem.STATUS = item.Acao == true ? "Aprovado" : item.Acao == false ? "Recusado" : "Pendente";

        lista.Add(lstParticipantePassagem);

    }


    excelHelper.Export<UploadPassagem>(lista);

    byte[] Excel = System.IO.File.ReadAllBytes(caminhoArquivo);            

    return new FileContentResult(Excel, "application/vnd.ms-excel");
}
 3
Author: , 2014-05-12 23:00:09

The most correct is to specify a Action in Controller that returns a FileResult. For example:

public FileResult ExportarExcel()
{
    // Monte aqui o arquivo Excel.
    // conteudoDoArquivo deve ser um byte[]

    return new File(conteudoDoArquivo, "application/vnd.ms-excel", "nomeDoArquivo.xls");
}
 2
Author: Leonel Sanches da Silva, 2014-05-12 17:40:21

Use like this!

 private void ExportarParaExcel(){

    DataTable odt = RetornaBuscaDoBanco();

    using (XLWorkbook wb = new XLWorkbook())
    {
        wb.Worksheets.Add(odt, "nomeaquivo");

        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;filename=nomeaquivo" + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + ".xlsx");
        using (MemoryStream MyMemoryStream = new MemoryStream())
        {
            wb.SaveAs(MyMemoryStream);
            MyMemoryStream.WriteTo(Response.OutputStream);
            HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
            HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
            HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
        }
    }
}
 1
Author: Marcelo Franco, 2020-05-08 16:36:50