简体   繁体   English

C#中的Excel工作表错误

[英]Excel sheet error in C#

I want to write some data to excelsheet file from datatable, i write this code 我想将一些数据从数据表写入excelsheet文件,我编写这段代码

    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. 我如何摆脱。

If the file already exists, you open it (to read), and then call SaveAs() with the same file. 如果该文件已经存在,则将其打开(以读取),然后使用相同的文件调用SaveAs() 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. 尝试写入其他路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM