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?

1
  • Is it a WinForms or WPF application? Or are you trying to do it in a C# Library / Console App? Commented Nov 6, 2013 at 22:26

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

3 Comments

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.
That's a FileDialog. C# has a class for that too.
I have edited my answer to incorporate what you asked about in comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.