0

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.

2
  • how to make it as writeable... am new to C#. brief advice will help me a lot. Commented Feb 3, 2014 at 12:15
  • This has nothing to do with C#. The problem is that your user account has no write access to that file. You will have to change the user permissions on your file Commented Feb 3, 2014 at 12:17

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This line gives me Error. 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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.