3

I need to create and save a Excel file without inform in the code the path and file name. So I can use the savefiledialog to show the save box to input the path and file name, but I can´t use it correctly. I tried to use the worksheet.saveas but this class doesn´t show the save box to input the path and file name. How can I save a excel file with that save box?

renato
  • 75
  • 1
  • 2
  • 7
  • Is it a WinForms or WPF application? Or are you trying to do it in a C# Library / Console App? – Shiva Nov 06 '13 at 22:26

1 Answers1

6

The basic mechanic of it is this:

public void SaveExcelWorkBook()
{
   OpenFileDialog openDlg = new OpenFileDialog();
   openDlg.InitialDirectory = @"C:\";
   openDlg.ShowDialog();
   string path = openDlg.FileName;

   if (openDlg.ShowDialog() == DialogResult.OK)
   {
      try
      {
         Application excelApp = new Application();
         Workbook workBook = excelApp.Workbooks.Open(path);
         Worksheet workSheet = (Worksheet)workBook.Worksheets[1];

         // Do your work here inbetween the declaration of your workbook/worksheet  
         // and the save action below.

         workBook.SaveAs(/*path to save it to*/);  // NOTE: You can use 'Save()' or 'SaveAs()'
         workBook.Close(); 
      }

      catch (Exception ex)
      {
      }
   }
}

I think I should also mention that Interop objects are unmanaged so, you will want to make sure that you are releasing them after calling .Close(). Here is an example:

Marshal.ReleaseComObject(workBook);

There are two fantastic tutorials for using Excel here and here. Good luck!

Community
  • 1
  • 1
Brian
  • 5,069
  • 7
  • 37
  • 47
  • Hi Brian, thanks for your answer, but I want that the user input the path and the name of the file. So it´s needs to show that box like when you click in the "save as" button in the Excel program. – renato Nov 07 '13 at 23:34
  • 2
    That's a `FileDialog`. C# has a [class](http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog(v=vs.110).aspx) for that too. – Brian Nov 07 '13 at 23:35
  • I have edited my answer to incorporate what you asked about in comments. – Brian Nov 07 '13 at 23:53