Home » excel » .net – Using C# to SaveAs Excel 2007 and up

.net – Using C# to SaveAs Excel 2007 and up

Posted by: admin May 14, 2020 Leave a comment


I included this:

using Excel = Microsoft.Office.Interop.Excel;

I would like to be able to open an Excel file XLSX and do a save it as a different file:

    xlWorkBook.SaveAs(xlWorkBook.Path + @"\XMLCopy.xls",

There are missing parameters above, and I do not understand what to enter for them!

Here’s my full code:

Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range;

            string str;
            int rCnt = 0;
            int cCnt = 0;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

Question: How can I save the Excel file with a different name/path using c# as above?

How to&Answers:

You need to use Visual Studios 2010 to properly use optional parameters in C#.

If you cannot use Visual Studios 2010 then Eddy’s suggestion Type.Missing should work.

When using methods with optional parameters (and not using Type.Missing) it is usually a good idea to use named parameters when calling the function.

Also, you should be aware of the limitations and quirks of optional parameters (though most of them should not affect you since you are not creating methods with optional parameters):

It should be noted that I do not recommend creating methods with optional parameters. Either overload the method or create a new object where the user can set the object properties before calling the method.