简体   繁体   中英

Saving Excel File as Read Only (Interop.Excel) C#

All,

I have the below code which opens a specified excel file deletes the first row and then saves it as a specified CSV.

However when it saves the CSV down it saves it in a read-only format. Can anyone advise how I would ensure the file is not saved down in read only format.

EDIT I have tried; To set the ReadOnly property to false.

I also am aware two instances of Excel may be opening which may cause the read only status from googling previous posts however including myApp.Quit() I believe it would close all instances of excel.

        public void DeleteRows(string OriginalFileName,String NewFileName)
    {
        Microsoft.Office.Interop.Excel.Application myApp;
        Microsoft.Office.Interop.Excel.Workbook myWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet myWorkSheet;
        Microsoft.Office.Interop.Excel.Range range;
        myApp = new Microsoft.Office.Interop.Excel.Application();
        myWorkBook = myApp.Workbooks.Open(OriginalFileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        myWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)myWorkBook.Worksheets.get_Item(1);
        range = (Microsoft.Office.Interop.Excel.Range)myWorkSheet.Application.Rows[1, Type.Missing];
        range.Select();
        range.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp);
        myApp.DisplayAlerts = false;
        myWorkSheet.SaveAs(NewFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
        myWorkBook.Close(true);
        myApp.Quit();
    }
}
}

保存excel文件时,尝试将ReadOnlyRecommended设置为false。

The solution was to change myWorkBook.Close(true); to myWorkBook.Close(false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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