1

I open an existing .xlsx file, make a change to it, and then save it back to disk. The change is working, but when I try to open the file (manually, by 2-clicking it in Windows Explorer), I get, "Excel cannot open the file 'Bla.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."

If I change the extension from "xlsx" to "xls" it opens just fine. But the original file is .xlsx, and I want to keep it that way. Here is my code:

// Open the file
MSExcel.Excel.ApplicationClass xlApp = new MSExcel.Excel.ApplicationClass();
MSExcel.Excel.Workbook xlBook = xlApp.Workbooks.Open(sourceFilename, 0, false, 5, null, null, false, MSExcel.Excel.XlPlatform.xlWindows, null, true, false, 0, true, false, false);
MSExcel.Excel.Sheets xlSheets = xlBook.Worksheets;
MSExcel.Excel.Worksheet xlSheet = (MSExcel.Excel.Worksheet)xlSheets.Item[1];

// Change the file
MSExcel.Excel.Range priceTypeCell = (MSExcel.Excel.Range)xlSheet.Cells[7, 3];
//if (priceTypeCell.Value2.ToString() == "Price Push") <= This is probably fine, but just in case...
if (priceTypeCell.Value2.ToString().Trim().Contains("Price Push"))
{
    priceTypeCell.Value2 = "Price Type";
}

// Save the file - example code showed xlWorkbookDefault, but that either never existed or
// has been deprecated; xlWorkbookNormal is what I chose from the limited available options
xlApp.DisplayAlerts = false; // Was prompting about overwriting the existing file
xlBook.SaveAs(sourceFilename, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing,
    false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlBook.Close();

What is wrong with the code I'm using? I adapted it from here (Igby Largeman's answer), but had to change xlWorkbookDefault, because that was not recognized. I tried both xlWorkbookNormal and xlExcel7, but both save as .xlsx but will only open if it is changed to .xls.

Oddly enough, perhaps, xlWorkbookDefault is indeed in the official list here (the last entry).

UPDATE

When I change the type to "Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet" (the closest to "xlOpenXMLWorkbook" that I found), I get an exception when the file thus saved is programmatically re-opened later:

System.Runtime.InteropServices.COMException was unhandled
  HelpLink=C:\Program Files (x86)\Microsoft Office\Office12\1033\XLMAIN11.CHM
  HResult=-2146827284
  Message=Excel cannot open the file 'ARAMARK-04-03-2016 DISTRIBUTOR COPY.xlsx' because the file format or file extension is not   
valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

UPDATE 2

When I tried to use "xlExcel9795", it wouldn't even save it. I got:

System.Runtime.InteropServices.COMException was unhandled
  HResult=-2146827284
  Message=Exception from HRESULT: 0x800A03EC
  Source=Microsoft.Office.Interop.Excel
  ErrorCode=-2146827284
  StackTrace:
       at Microsoft.Office.Interop.Excel.WorkbookClass.SaveAs(Object Filename, Object FileFormat, Object Password, Object WriteResPassword, Object ReadOnlyRecommended, Object CreateBackup, XlSaveAsAccessMode AccessMode, Object ConflictResolution, Object AddToMru, Object TextCodepage, Object TextVisualLayout, Object Local)
       at PricePushETLProcess.PricePushFile.ChangeColumnHeaderVal(PricePushFile ppf) in . . .
Community
  • 1
  • 1
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

2 Answers2

3

You are saving it as Excel 95 - see this:

https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.xlfileformat.aspx

Change Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7 to a newer format.

I believe the most current format would be Excel.XlFileFormat.xlOpenXMLWorkbook

snow_FFFFFF
  • 3,235
  • 17
  • 29
0

This works:

xlBook.SaveAs(sourceFilename, Type.Missing, Type.Missing, Type.Missing,
    false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

(punt).

IOW, rather than specify a type of Excel file, just leave it blank or default by assigning "Type.Missing" to that (second) argument in the call to SaveAs().

Here's the whole dadblasted thing:

public void ChangeColumnHeaderVal()
{
    MSExcel.Excel.ApplicationClass xlApp = null;
    MSExcel.Excel.Workbook xlBook = null;
    MSExcel.Excel.Worksheet xlSheet = null;
    try
    {
        // Open the file
        xlApp = new MSExcel.Excel.ApplicationClass();
        xlBook = xlApp.Workbooks.Open(sourceFilename, 0, false, 5, null, null, false, MSExcel.Excel.XlPlatform.xlWindows, null, true, false, 0, true, false, false);
        var xlSheets = xlBook.Worksheets;
        //Get the first Sheet
        xlSheet = (MSExcel.Excel.Worksheet)xlSheets.Item[1];

        // Change the file
        MSExcel.Excel.Range priceTypeCell = (MSExcel.Excel.Range)xlSheet.Cells[7, 3];
        //if (priceTypeCell.Value2.ToString() == "Price Push") <= This is probably fine, but just in case...
        if (priceTypeCell.Value2.ToString().Trim().Contains("Price Push"))
        {
            priceTypeCell.Value2 = "Price Type";
        }

        // Save the file
        xlApp.DisplayAlerts = false; // Was prompting about overwriting the existing file
        xlBook.SaveAs(sourceFilename, Type.Missing, Type.Missing, Type.Missing,
            false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        xlBook.Close();
    }
    finally
    {
        // Cleanup
        if (xlSheet != null) Marshal.ReleaseComObject(xlSheet);
        if (xlBook != null) Marshal.ReleaseComObject(xlBook);
        if (xlApp != null) xlApp.Quit();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862