Apr 7, 2012

Excel Interop Error Code -2146827284

I was trying to to a Save As to save off an Excel file to disk so that I could have it attached to an email. It turns out you have to be pretty careful to match the file extension of the saved file to the Excel format. I suppose the correct match depends on the version of Office that you have installed I was trying to use the  XlFileFormat.xlWorkbookNormal enum to save to an .xls file in Office 2010 and it turns out this was causing the above error.  I ended up using

Save as workbook default .xlsx
object save_format = XlFileFormat.xlWorkbookDefault;
_workbook.SaveAs(filename, save_format);

where filename had a file extension of .xlsx and the error went away. Eventually I realized a better approach was to not specify the extension at all, but to let Excel figure it out for me.  I need the full final filename when I'm done because I want to attach the file to an email. Luckily the workbook's FullName property will do just that

Let Excel Set Extension
  1. var file_path_no_ext = fullFilePath.PathWithoutExtension();
  2. object save_format = XlFileFormat.xlWorkbookDefault;
  3. _workbook.SaveAs(file_path_no_ext, save_format);
  4. saved_file_path = _workbook.FullName;

PathWithoutExtension is just a simple string extension method I wrote that looks like this:

  1. public static string PathWithoutExtension(this string value)
  2. {
  3.     var filename_no_ext = Path.GetFileNameWithoutExtension(value);
  4.     var root = Path.GetDirectoryName(value);
  5.     var file_path_no_ext = Path.Combine(root, filename_no_ext);
  6.     return file_path_no_ext;
  7. }

Also thanks to an answer on Stack Overflow I was also able to export to a PDF using this code:

Export as PDF
if (_reportParameters.SaveAttachmentsAsPDF)
     filename = Path.ChangeExtension(filename, "pdf");
     _worksheet1.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, filename,

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.