Download excel file

Asked

Viewed 1,297 times

4

I created an excel file, but now the user needs to download, how can I do ? follows 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);
    }
  • I think in this case we can abstract the generation of the file. You could leave a smaller pseudo-code where it assumes that the file will be created correctly.

4 answers

3

Let’s say you created in a folder within your project Arquivo. Inside it has a file EXCEL(xls) by the name of Pasta1.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 his 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");
}

2


Using Epplus, here’s how I’m doing:

var memoryStream = package.GetAsByteArray();

return base.File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); //fileName é o nome do teu ficheiro

2

The most correct is to specify a Action in the Controller return 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");
}
  • Dear my file content is a List, as it turns it into byte[] ??

  • @Sirsmart What is the return of this line? excelHelper.Export<UploadPassagem>(lista);

  • I have no return from this line... I’m sorry but I still don’t understand where you’re going...

  • I don’t know how it works, you ExcelHelper, but I suppose it returns an object that represents the Excel file built in some way. You need to represent it as an array of bytes so that it can be returned. Once you have done this array of bytes, put it in place of conteudoDoArquivo that by calling Action ExportarExcel do seu Controller`, the result will be a download.

1

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.
        }
    }
}

Browser other questions tagged

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