Try to open my Excel file using C# and get an error

后端 未结 3 1162
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 04:42

I try to read my Exel file from code and received System.InvalidCastException:

Additional information: Unable to cast COM object of type \'System.__Co

相关标签:
3条回答
  • 2021-01-29 04:59

    Seems like you are using

        Microsoft.Office.Tools.Excel.Worksheet 
    

    instead of

        Microsoft.Office.Interop.Excel.Worksheet
    

    which is why you are getting an invalid cast exception.

    0 讨论(0)
  • 2021-01-29 05:13

    Try the below code and see if it works, if not let us know what problems you have:

    using Excel = Microsoft.Office.Interop.Excel;
    
    namespace Excel_Sample
    {
        public partial class YourClass
        {
            Excel.Application appExcel;
            Excel.Workbook newWorkbook;
            Excel.Worksheet objsheet;
            string file = @"D:\file.xlsx";
    
            static void excel_init()
            {
                if (System.IO.File.Exists(file))
                {
                    //Start Excel and get Application object.
                    appExcel = new Excel.Application();
                    //Get a workbook.;
                    newWorkbook = (Excel.Workbook)(appExcel.Workbooks.Open(file));
    
                    int count = newWorkbook.Worksheets.Count;
                    if (count > 0)
                    {
                        //Get Your Worksheet
                        objsheet = (Excel.Worksheet)newWorkbook.ActiveSheet;
                    }
                }
                else
                {
                    MessageBox.Show("Unable to open file!");
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
                    appExcel = null;
                    System.Windows.Forms.Application.Exit();
                }
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-29 05:15

    Workbook.ActiveSheet Property might not be the best choice for programmatically opened Excel files as it can actually return a non-Worksheet object

    You might want to consider checking sheets count and using indexes:

    int count = newWorkbook.Worksheets.Count;
    if (count > 0)
    {
        objsheet = (Worksheet) newWorkbook.Worksheets[1];
    }
    

    And try not to break the 2-dot rule - you'll need to release all you COM's to properly close your app and Excel.

    Edited:

    You could be mixing Microsoft.Office.Interop.Excel with Microsoft.Office.Tools.Excel namespaces.

    Try to declare and assign as follows:

    private static Microsoft.Office.Interop.Excel.Worksheet objsheet = null;
    ...
    objsheet = (Microsoft.Office.Interop.Excel.Worksheet) newWorkbook.Worksheets[1];
    
    0 讨论(0)
提交回复
热议问题