C#使用Microsoft.Office.Interop.Excel读取数据

时间:2016-09-20 06:40:41

标签: c# arrays excel

我有一个数据表,我需要根据用户输入从excel中读取数据并将其作为数组存储在VS中。

如果用户输入C1,请搜索并获取相关数据:

array [0]:X1E1M101

数组[1]:F2G1M202

如果用户输入C2:

array [0]:X1E1M105

数组[1]:F1G2M304

我的数据:

     A      B      C     D     E
1   C1
2
3   X1     E1     M1     01 
4   F2     G1     M2     02
5
6   C2
7
8   X1     E1     M1     05 
9   F1     G2     M3     04
10

我的代码:

//I declared the Interop
using Excel = Microsoft.Office.Interop.Excel;


        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        Excel.Range range;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Open(ManufacturingFile);
        //xlWorkSheet = ("Default Value");  // i get an error here when trying to define the worksheet name i want to select. "Cannot impicitly convert type string to ... excel.worksheet'

        xlWorkSheet = ((Excel.Worksheet)this.Application.ActiveWorkbook.Sheets[1]).Select(); // This method also I get an error.
        xlWorkSheet.Activate(); 

由于我是使用Interop的新手,因此我被困在这部分之后。 希望有人可以帮助我,我是C#的初学者,非常感谢你的帮助。

2 个答案:

答案 0 :(得分:2)

你必须打开你的woorkbook和工作表,有很多例子解释如何做到这一点,这里有一个样本

      Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        Excel.Range range;

        string str;
        int rCnt = 0;
        int cCnt = 0;

        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Open("testone.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);


        range = xlWorkSheet.UsedRange;

        Microsoft.Office.Interop.Excel.Range xlFound =range.EntireRow.Find("C2",misValue, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart,Excel.XlSearchOrder.xlByColumns,Excel.XlSearchDirection.xlNext,true, misValue, misValue);

        if (!(xlFound == null))
        {
            int ID_Number = xlFound.Column;
            int rownum = xlFound.Row;
            Console.WriteLine(ID_Number);
            Console.WriteLine(rownum);
            Console.Read();
        }

如果' C1'你可以首先得到搜索的范围值。在a1处,您必须从(n + 2)读取整行,并在找到空行时停止。

以上代码未编译自here

答案 1 :(得分:1)

如果您只是从excel文件中读取数据,我建议您使用 ExcelDataReader 库,它提供更好的性能,并且不会留下ghost进程而不是互操作一。这里有一些示例代码可供您设置:

    IExcelDataReader reader = null;

    string FilePath = "PathToExcelFile";

    //Load file into a stream
    FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read);

    //Must check file extension to adjust the reader to the excel file type
    if (System.IO.Path.GetExtension(FilePath).Equals(".xls"))
    {
        reader = ExcelReaderFactory.CreateBinaryReader(stream);
    }
    else if (System.IO.Path.GetExtension(FilePath).Equals(".xlsx"))
    {
        reader = ExcelReaderFactory.CreateBinaryReader(stream);
    }

    if (reader != null)
    {
        //Fill DataSet
        System.Data.DataSet result = reader.AsDataSet();
        try
        {
            //Loop through rows for the desired worksheet
            //In this case I use the table index "0" to pick the first worksheet in the workbook
            foreach (DataRow row in result.Tables[0].Rows)
            {
                string FirstColumn = row[0].ToString();
            }
        }
        catch
        {

        }
    }