如何从MS Excel表格中检索数据?

时间:2014-08-25 05:28:01

标签: c# excel

我正在尝试使用下面的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);
             }

        }

2 个答案:

答案 0 :(得分:1)

  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();

答案 1 :(得分:0)

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);

        }