How to save an XLSX (Excel) file instead of CSV?

3

Today I have the code below, which saves a file in CSV format. What do I need to change to save in XLSX (Excel) format?

public static void buildCSV(string filename = "resultado.xlsx")
        {
            Console.WriteLine("Escrevendo no arquivo.");

            StringBuilder csvBuilder = new StringBuilder();

            //cria o header
            csvBuilder.AppendLine("Nome;Cpf;Cep;ID Cliente");

            foreach (var item in BAG)
            {
                csvBuilder.AppendLine(item);
            }

            File.WriteAllText(filename, csvBuilder.ToString(), Encoding.UTF8);
        }
    }
}
    
asked by anonymous 30.11.2018 / 22:23

1 answer

5

You can do this by using the Excel interop library ( Microsoft.Office.Interop.Excel.dll ), but for this Excel will have to be installed on the computer running your application.

To use this code, you must first reference the Microsoft.Office.Interop.Excel namespace. An easy way to do this is by using NuGet. In Visual Studio, go to the Tools > NuGet Package Manager > Manage NuGet Packages for Solution > Browse, search for Microsoft.Office.Interop.Excel and install the package. Or like

The code to create the XLSX file is this:

using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

   public static void CriarArquivoXlsx(string filename = "resultado.xlsx")
   {
      _CriarArquivoXlsx(filename);

      // Libera os objetos COM do Excel.
      GC.Collect();
      GC.WaitForPendingFinalizers();
   }

   private static void _CriarArquivoXlsx(string filename)
   {
      Excel.Application xlApp = new Excel.Application();
      if (xlApp == null)
      {
         MessageBox.Show("Excel não está instalado!");
         return;
      }

      Excel.Workbook xlWorkbook = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
      Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];

      // Cabeçalho.
      // A indicação da coluna pode ser por números (1, 2, 3, etc.)
      // ou por texto ("A", "B", "C", etc.).
      int row = 1;
      xlWorksheet.Cells[row, 1] = "Nome";
      xlWorksheet.Cells[row, 2] = "Cpf";
      xlWorksheet.Cells[row, 3] = "Cep";
      xlWorksheet.Cells[row, 4] = "ID Cliente";

      foreach (string item in BAG)
      {
         row++;
         int col = 0;
         foreach (string campo in item.Split(';'))
         {
            col++;
            xlWorksheet.Cells[row, col] = campo;
         }
      }

      xlWorkbook.SaveAs(filename, XlFileFormat.xlOpenXMLWorkbook);

      xlWorkbook.Close();
      xlApp.Quit();
   }

I created the private function _CriarArquivoXlsx() , which does the actual work, and the public function CriarArquivoXlsx() , which calls the private function and then fires the GC (GarbageCollector) to release the references of the created COM objects in the private function.

This is important because because the Office interop library creates COM objects that are managed by the .NET, and therefore by the .NET Garbage Collector, the Excel process can be "hung" for an indefinite period of time when the application is running. This is why you need to force an immediate garbage collection, thus releasing COM object references from Excel.

The fact that you have put the garbage collection out of the function that creates the COM objects is merely a trick for this to work correctly also in the debug mode of the application, see #

References used to create the code:

There is also an open source library that allows you to create XLSX files without needing Excel installed, called EPPlus . More details here:

01.12.2018 / 01:44