【问题标题】:Invalid Index. Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX) when Workbooks.Open无效索引。来自 HRESULT 的异常:Workbooks.Open 时出现 0x8002000B (DISP_E_BADINDEX)
【发布时间】:2014-03-24 11:17:36
【问题描述】:

我正在尝试制作一个可以打开xlsx 文件进行阅读的应用程序,然后阅读它并用它做一些事情。当我运行我的应用程序并单击按钮加载文件时,我收到此错误:

无效索引。 HRESULT 异常:0x8002000B (DISP_E_BADINDEX)

在这行代码上:

Excel.Workbook a
   = excelApp.Workbooks.Open("C:\\test.xlsx", 0, true, 5, "", "", true,
                             Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
                             "\t", false, false, 0, true, 1, 0);

你能建议这里有什么问题吗?

编辑:这是完整的代码,所以我希望能更容易地判断导致错误的原因

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Windows.Forms;
 using Excel = Microsoft.Office.Interop.Excel;
 using System.Reflection;


 namespace WindowsFormsApplication2
 {
     public partial class Form1 : Form, IDisposable
     {
         public Form1()
         {
             InitializeComponent();
         }

         private void button1_Click(object sender, EventArgs e)
         {
             Excel.Application excelApp = new Excel.Application();
             excelApp.Visible = true;

             Excel.Workbook a = excelApp.Workbooks.Open("C:/test.xlsx");


        // This selectes the used range of the excel workbook and enters it in
        // a two dimentional array
        try
        {
            // Get a reference to the first sheet of the workbook.
            Excel.Sheets excelSheets = a.Worksheets;
            string currentSheet = "Sheet1";
            Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);

            // write out to console for debugging
            textBox1.Text = "excelWorksheet is " + excelWorksheet;

            // Get a range of data.
            Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range("A3", Missing.Value);

            // write out to console for debugging
            textBox1.Text = "excelCell is " + excelCell;

            // write out to console for debugging
            textBox1.Text = "Creating string[,] array. . . ";
            // Retrieve the data from the range.
            Object[,] dataArray;
            // write out to console for debugging
            textBox1.Text = "String[,] array created. . . ";

            dataArray = (System.Object[,])excelCell.get_Value(Missing.Value);

            // write out to console for debugging
            textBox1.Text = "Counting rows and columns. . . ";
            // Determine the dimensions of the array.
            int iRows;
            int iCols;
            iRows = dataArray.GetUpperBound(0);
            iCols = dataArray.GetUpperBound(1);

            // write out to console for debugging
            textBox1.Text = "Printing array. . . ";
            // Print the data of the array.
            for (int rowCounter = 1; rowCounter <= iRows; rowCounter++)
            {
                // write out to console for debugging
                textBox1.Text = ("row " + rowCounter);
                for (int colCounter = 1; colCounter <= iCols; colCounter++)
                {

                    // Write the next value to the console.
                    richTextBox1.Text = "col " + colCounter + "= " + dataArray[rowCounter, colCounter].ToString() + ", ";
                }
                // Write in a new line.
                richTextBox1.Text = "\n";

            }
        }
        catch (Exception theException)
        {
            // Create error message
            String errorMessage;
            errorMessage = "Error: ";
            errorMessage = String.Concat(errorMessage, theException.Message);
            errorMessage = String.Concat(errorMessage, " Line: ");
            errorMessage = String.Concat(errorMessage, theException.Source);
            // Display error message
            MessageBox.Show(errorMessage, "Error");
         }

       }
    }
  }

【问题讨论】:

  • 你为什么要传递所有这些参数。你不是只想传递文件名吗?
  • 只有文件路径作为参数的相同错误
  • 该陈述没有错,也没有可能的错误。更有可能是下一个。
  • Hans Passant - 我已经编辑了我的问题并提供了完整的代码。你能看看吗?谢谢

标签: c# excel


【解决方案1】:

我不知道您是否找到了解决方案,但这是一种解决方法。希望能帮助到你 我面临着完全相同的问题。 问题出在这条线上。在我的情况下,工作簿有多个工作表,因此我想遍历每个工作表并检索数据。

string currentSheet = "Sheet1";
        Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);

您正在尝试打开一个不存在的索引/名称为“Sheet1”的工作表。如果您已经知道您期望的工作表名称,请继续使用这些名称,否则最好使用工作表索引。 例子

Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(1);

这将获取索引 1 处的工作表

这就是我解决我的问题的方法。我首先检查工作表名称是否存在

var sheetExists = xlWorkBook.Worksheets.Cast<Excel.Worksheet>().FirstOrDefault(worksheet => worksheet.Name == "SomeSheetName"); // this line returns null if the sheet name or index you intend to open does not exist

                        if (sheetExists != null) // this line thus handles the invalid index error. 
                        { /**you can now open the sheet**/
                          Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
                       }

【讨论】:

    【解决方案2】:

    我相信 sheetExists 变量已经有工作表,所以不需要再次获取它,所以如果 sheetExists 不为空,则可以使用

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多