Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to Save Excel File Using C#

Tags:

c#

excel

save

I'm trying to modify and save data in Excel. With the code below, I'm accessing the sheet, performing modifications, then saving the file. I'm unable to save the file. Here is my code:

Application excel = new Application();
        excel.Visible=true;
        Workbook wb = (Workbook)excel.Workbooks.Open(@"C:\Users\dnyanesh.wagh\Desktop\BookExcel1.xlsx");
        Worksheet ws = (Worksheet)wb.Worksheets[1];
        ws.Cells[1, 1] = "sagar";
        ws.Cells[2, 1] = "sagar";
        ws.Cells[3, 1] = "sagar";
        wb.Save();
        wb.close();

I'm receiving this error: "the file named 'BookExcel1.xlsx' already exists in this location. Do you want to replace it?"

So I changed the code to:

Workbook wb = (Workbook)excel.Workbooks.Open(@"C:\Users\dnyanesh.wagh\Desktop\BookExcel1.xlsx",0, false, 5, "", "",
            false, XlPlatform.xlWindows, "", true, false,
            0, true, false, false););

Then error is: "BookExcel1.xlsx is being modified by user_name.open as read only". If I click the 'cancel' button, I receive the exception above with "Exception from HRESULT: 0x800A03EC"

I have also tried:

wb.SaveAs(@"C:\Users\dnyanesh.wagh\Desktop\BookExcel1.xlsx");
wb.Close(true,null,null);

From that I receive the same error, with the above file showing the modifications.

Can anybody tell me how can I save the file with modifications?

like image 345
dnyaneshwar Avatar asked Oct 04 '22 03:10

dnyaneshwar


1 Answers

Check that you don't already have an Excel.exe process runnning. Also, you should open the workbook so that it's editable.

This code works:

string txtLocation = Path.GetFullPath(InputFile);

object _missingValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application excel = new   Microsoft.Office.Interop.Excel.Application();
Excel.Workbook theWorkbook = excel.Workbooks.Open(txtLocation,
                                                        _missingValue,
                                                        false,
                                                        _missingValue,
                                                        _missingValue,
                                                        _missingValue,
                                                        true,
                                                        _missingValue,
                                                        _missingValue,
                                                        true,
                                                        _missingValue,
                                                        _missingValue,
                                                        _missingValue);

//refresh and calculate to modify
theWorkbook.RefreshAll();
excel.Calculate();
theWorkbook.Save();
theWorkbook.Close(true);
excel.Quit();
like image 97
Alex Avatar answered Oct 07 '22 20:10

Alex