如何从MS Excel工作表中检索数据

本文关键字:检索 数据 工作 Excel MS | 更新日期: 2023-09-27 18:19:26

我正在尝试使用下面的C#代码从excel中获取数据。我从两个值中得到值列转换为单个变量(str)。

我想把这个值放入不同的变量中,这样我就可以在运行时为两个不同的语句发送这个值。

如何将它们转换为两个不同的变量?

 string currentSheet = "Sheet1";
        excelApp = new Excel.Application();
        //Opening/adding Excel file
        excelWorkbook = excelApp.Workbooks.Add(workbookPath);
        excelSheets = excelWorkbook.Sheets;
        excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
        //Gives the used cells in the sheet
        range = excelWorksheet.UsedRange;
        for (rowCnt = 1; rowCnt <= range.Rows.Count; rowCnt++)
        {
            for (colCnt = 1; colCnt <= range.Rows.Count;colCnt++)
            {
                str = (string)(range.Cells[rowCnt,colCnt] as Excel.Range).Value2;
                System.Console.WriteLine(str);
             }
        }

如何从MS Excel工作表中检索数据

  string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='"Excel 12.0;HDR=Yes;IMEX=1'";";
        OleDbConnection con = new OleDbConnection(Connection);
        OleDbCommand command = new OleDbCommand();
        System.Data.DataTable dt = new System.Data.DataTable();
        OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", con);
        myCommand.Fill(dt);
        con.Close();
for (rowCnt = 1; rowCnt <= range.Rows.Count; rowCnt++)
        {
            string Charity = (string)(range.Cells[rowCnt, 1] as Excel.Range).Value; 
            string Country = (string)(range.Cells[rowCnt, 2] as Excel.Range).Value; 
            System.Console.WriteLine(Charity + " --- " + Country);
        }