web developpment .net c# Save/Download Excel Document

alfinete

Power Member
Bom dia

estou a gerar um excel através de html referente á variiável FinalWord onde tenho o html gerado .

no exemplo do code abaixo sera enviado no browser o ficgeiro para download ao qual funciona tdo ok .

Código:
     string FinalWord = "<table><tr><td>Nome<\"td><td>Email<\"td><\"tr><tr><td>alf<\"td><td>[email protected]<\"td><\"tr><tr><td>alf1<\"td><td>[email protected]<\"td><\"tr><tr><td>alf2<\"td><td>[email protected]<\"td><\"tr><tr><td>alf3<\"td><td>[email protected]<\"td><\"tr><\"table>";
        string ActualDate = DateTime.Now.ToString("yyyyMMdd_hhmm");
      string ID =  12345;
        string  StartFileName = string.Format("Ficheiro_Teste {0}_",ID );
        string  Extention = "xls";
        string  FileName = string.Format("{0}{1}.{2}", StartFileName, ActualDate, Extention);
        string  SheetName = string.Format("{0}{1}", StartFileName, ActualDate);


        Context.Response.Clear();
        Context.Response.ClearContent();
        Context.Response.ClearHeaders();
        Context.Response.Buffer = true;

        Context.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", FileName));
        Context.Response.Charset = string.Empty;
        Context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Context.Response.Write(FinalWord);
        Context.Response.Flush();
        Context.ApplicationInstance.CompleteRequest();
        Context.Response.End();



o que quero fazer agora é com um code parecido a este
gerar este doc e guardar o mesmo numa folder á minha escolha , e o download não ser enviado para o browser


aguardo por uma ajuda
 
Resolvi da seguinte forma
instalando o package nugat "Microsoft.Office.Interop.Excel"

guardando a string html table num file html
e criando um excel baseado nessa html

____________________________

Código:
Snippetusing Excel = Microsoft.Office.Interop.Excel;


Snippet/// <summary>
      ///  Criamos um ficheiro excel através do conteudo de um ficheiro html
      /// </summary>
      /// <param name="FileContent">COnteudo do ficheiro a ser criado</param>
      /// <param name="PathFile">Caminho onde crimamos quer o html quer p excel</param>
      /// <param name="FileName">Nome do focheiro html</param>
      /// <param name="ExcelFileName">Nome do ficheiro Excel</param>
      ///
      /// <returns> True ou false no caso de criar ou não o respectivo ficheiro</returns>
 
      public bool  CreateExcelBuHtmlString( string FileContent, string PathFile  , string HtmlFileName, string ExcelFileName)
      {
 
 
          bool ISCreate = false;
 
          string TxtFile = string.Format("{0}{1}", PathFile, HtmlFileName);
          string ExcelFile = string.Format("{0}{1}", PathFile, ExcelFileName);
 
          try
          {
              // Criar o ficheiro Html
              CreateFileHtmlWIthCOntent(FileContent, PathFile, HtmlFileName);
 
              if (File.Exists(TxtFile))
              {
                  // criação do focheiro excel
                  var app = new Excel.Application();
                  var wb = app.Workbooks.Open(Filename: TxtFile);
                  wb.SaveAs(Filename: ExcelFile, FileFormat: XlFileFormat.xlOpenXMLWorkbook);
                  wb.Close();
                  // Apagar ficheiro txt
                  File.Delete(TxtFile);
                  ISCreate = true;
              }
 
          }
          catch (Exception ex)
          {
               
          }
 
          return ISCreate;
      }
 
 
      /// <summary>
      /// Criação de Um ficheiro
      /// </summary>
      /// <param name="FIleContent"> COnteudo do ficheiro</param>
      /// <param name="PathHtmlFile">Caminho onde vamos criar o ficheiro</param>
      /// <param name="HtmlFileName">Nome do Ficheiro COm extensão</param>
      public void CreateFileHtmlWIthCOntent(string FileContent, string PathHtmlFile, string HtmlFileName)
      {
 
          StringBuilder sbContentFile = new StringBuilder();
 
          sbContentFile.Append(FileContent);
          StreamWriter swFile = new StreamWriter(PathHtmlFile + @"\" + HtmlFileName );
 
          swFile.Write(sbContentFile);
          swFile.Flush();
          swFile.Close();
          swFile.Dispose();
 
 
      }

Chamada
________________________

Código:
Snippetstring HtmlTable        = @"<table><tr><td>Nome</td><td>Email</td></tr><tr><td>alf</td><td>[email protected]</td></tr><tr><td>alf1</td><td>[email protected]</td></tr><tr><td>alf2</td><td>[email protected]</td></tr><tr><td>alf3</td><td>[email protected]</td></tr></table>";
          string PathFile         = @"c:\Testes\";
          string HtmlFileName     = "Excel.html";
          string ExcelFileName    = "Excel.xls";
 
 
 
 
          CreateExcelBuHtmlString(HtmlTable, PathFile,HtmlFileName  , ExcelFileName  );
 
Back
Topo