使用C#从Excel单元格检索数据

时间:2011-02-21 19:55:25

标签: c# excel

请查看下面的代码,我试图用C#获取excel工作表单元格值。但是,当我检查立即窗口中的值时,它们根本不匹配实际值。有些是空的。为什么?谢谢你的建议。

string fname;
    int nRows;
    int nCols;
    private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWookSheet1;
        Excel.Range xlRange;

        openFileDialog1.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx";
        openFileDialog1.Title = "Select an excel file";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
            fname = openFileDialog1.FileName;
        System.IO.FileInfo fi = new System.IO.FileInfo(fname);
        string ext = fi.Extension.ToString();
        xlApp = new Excel.ApplicationClass();
        string parameter;
        if (ext == ".xls")
            parameter = "5";
        else
            parameter = "51";
        xlWorkBook = xlApp.Workbooks.Open(fname, 0, true, parameter, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWookSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        object misValue = System.Reflection.Missing.Value;


        xlRange = xlWookSheet1.UsedRange;
        if (xlRange != null)
        {
            nRows = xlRange.Rows.Count;
            nCols = xlRange.Columns.Count;
            xlRange = (Microsoft.Office.Interop.Excel.Range)xlWookSheet1.Cells[nRows, nCols];
        }

        Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
        List<string> list1 = new List<string>();
        for (int i = 1; i < nCols; i++)
        {
            string temp = (string)(xlRange.Cells[1, i] as Excel.Range).Value2; 
            // wrong values from temp
            list1.Add(temp);
        }

2 个答案:

答案 0 :(得分:3)

using System.Data.OleDb;
using System.Data;


public DataTable GetDataTableFromExcel(string FilePath, string strTableName)
        {
            string XLSConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
            //string XLSConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
            OleDbConnection XLSCon = new OleDbConnection(XLSConnectionString);
            OleDbDataAdapter XLSDataAdp = new OleDbDataAdapter();
            XLSDataAdp.SelectCommand = new OleDbCommand();
            XLSDataAdp.SelectCommand.Connection = XLSCon;
            try
            {
                DataTable dtXLSData = new DataTable();
                XLSCon.Open();
                XLSDataAdp.SelectCommand.CommandText = "SELECT * FROM [" + strTableName + "$]";
                XLSDataAdp.Fill(dtXLSData);

                return dtXLSData;

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                XLSCon.Close();
            }
        }

试试这个...传递文件路径和工作表名称 然后以简单的方式或LINQ方式解析数据表

答案 1 :(得分:0)

我相信罪魁祸首将在线下:

xlRange = (Microsoft.Office.Interop.Excel.Range)xlWookSheet1.Cells[nRows, nCols];

这会将您的范围折叠到一个单元格 - 您可以通过检查xlRange.Rows.Count来快速测试它。我建议你删除这一行,代码应该工作。您可能觉得有用的另一个技巧是Range.Value属性将返回值数组,如果范围有多个单元格。