日期:2014-05-18  浏览次数:21618 次

C#读取Excel报错:exception from HRREULT
C# code

Object Nothing = Missing.Value;
            //WdSaveFormat 为Excel文档的保存格式 
            object format = Excel.XlFileFormat.xlOpenXMLWorkbook;
            Excel.XlFileFormat version = Excel.XlFileFormat.xlExcel8;
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "Excel文档(*.xlsx)|*.xlsx|Excel97-2003文档(*.xls)|*.xls";
            if (System.Windows.Forms.DialogResult.OK == openFile.ShowDialog())
            {
                string path = openFile.FileName;//文件路径变量 
                if (System.IO.Path.GetExtension(path).ToLower() == ".xlsx")
                {
                    version = Excel.XlFileFormat.xlOpenXMLWorkbook;
                }
                try
                {
                    Excel.Application excelApp = new Excel.Application();               //Excel应用程序变量 
                    Excel.Workbook excelBook = excelApp.Workbooks.Open(path, version, Nothing, Nothing, Nothing, Nothing, Excel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);
                    Excel.Worksheet excelSheet = (Excel.Worksheet)excelApp.ActiveSheet;
                    Excel.Range test = (Excel.Range)excelSheet.Cells[1, 1];
                    MessageBox.Show(test.Value2.ToString());
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Excel创建失败!\n原因:" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }



------解决方案--------------------
下断点调试看哪一行报错。也可能是dll版本与当前安装office版本不一样引起的异常。