user3226735
user3226735

Reputation: 11

Excel sheet error in C#

I want to write some data to excelsheet file from datatable, i write this code

    string path = "D:\\Project\\SMCCampaignmgmt\\trunk\\UserFolder\\NewFolder\\saran.xlsm";
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = false;
    oXL.DisplayAlerts = false;
    oXL.UserControl = false;
    //error on this line
    if (!File.Exists(path))
    {
        mWorkBook = oXL.Workbooks.Add();
    }
    else
    {


        mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
    }
    mWorkSheets = mWorkBook.Worksheets;

    //Get the allready exists sheet
    mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Template");

    Microsoft.Office.Interop.Excel.Range range = mWSheet1.UsedRange;


    mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
    Missing.Value, Missing.Value, true, true, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
    false,false, Missing.Value,
    Missing.Value, Missing.Value);
    mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
    mWSheet1 = null;

    mWorkBook = null;

    oXL.Quit();
    GC.WaitForPendingFinalizers();
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();

But am getting the error as Cannot access the file, because its readonly. How i can get rid.

Upvotes: 0

Views: 210

Answers (1)

w5l
w5l

Reputation: 5746

If the file already exists, you open it (to read), and then call SaveAs() with the same file. Probably you get the readonly error there (you didnt specify which line gave the error), because the file is already open and cannot be overwitten. Try writing to a different path.

Upvotes: 1

Related Questions