0

这是我在 C# 中的第一个控制台应用程序项目,我正在尝试将 Excel 工作表的使用区域导入二维数组。这可能不是最有效的方法,但这是我到目前为止的代码。

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; 

Excel.Application excelApp = new Excel.Application();
        excelApp.Visible = true;
        string workbookPath = "C:/Users/Snuge/Desktop/CourseNumbersNoWSReg.xlsx";
        Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
                0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);

        // 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 = excelWorkbook.Worksheets;
            string currentSheet = "Sheet1";
            Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);

            // write out to console for debugging
            Console.WriteLine("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
            Console.WriteLine("excelCell is " + excelCell);

            // write out to console for debugging
            Console.WriteLine("Creating string[,] array. . . ");
            // Retrieve the data from the range.
            Object[,] dataArray;
            // write out to console for debugging
            Console.WriteLine("String[,] array created. . . ");

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

            // write out to console for debugging
            Console.WriteLine("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
            Console.WriteLine("Printing array. . . ");
            // Print the data of the array.
            for (int rowCounter = 1; rowCounter <= iRows; rowCounter++)
            {
                // write out to console for debugging
                Console.WriteLine("row " + rowCounter);
                for (int colCounter = 1; colCounter <= iCols; colCounter++)
                {

                    // Write the next value to the console.
                    Console.WriteLine("col " + colCounter + "= " + dataArray[rowCounter, colCounter].ToString() + ", ");
                }
                // Write in a new line.
                Console.WriteLine("\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");
        }

我插入了 Console.Writeline(); 用于调试目的。正确的 Excel 工作簿打开,我在命令提示符下获得的输出是

excelWorksheet is System.__ComObject 
excelCell is System.__ComObject 
Creating string[,] array. . . 
String[,] array created. . .

然后会弹出一个带有消息的消息框

"Error: Cannot convert type 'string' to object[*,*] Line: Anonymously Hosted DynamicMethods Assembly".    

这行代码给了我一个错误,我不知道为什么。

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

有人可以为我提供这个问题的解决方案吗?

此外,是否有代码在命令提示符中显示一个值而不是“System.__ComObject”?

我正在使用 Excel 2007,并添加了 Microsoft Excel 12.0 对象库参考。

4

2 回答 2

1

我想你可以使用

// This value "should" be boxed into two-dimensional array
object dataArray = excelCell.Value;

或者

var dataArray = (object[,])excelCell.Value2;
于 2012-04-12T08:52:10.827 回答
0

错误说明了一切,它无法将字符串类型的值(显然是单元格中的数据)转换为二维数组。你为什么要这么投呢?不需要数组,然后您就可以读取单个单元格。但是,如果您的范围包含多个单元格,则返回的结果实际上将是二维数组。

然后你需要这样的东西:

object[,] result;
object rawData = excelCell.get_Value(Missing.Value);
if(rawData.GetType().IsArray())
{
    result = rawData;
}
else
{
    result = CreateArrayFromValue(rawData);
}

return result;

当然你需要CreateArrayFromValue自己实现。

于 2012-04-12T08:53:28.367 回答