简体   繁体   English

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

[英]Retrieving data from Excel cells with C#

please look at my code below, I tried to get the excel worksheet cells values with C#. 请查看下面的代码,我尝试使用C#获取excel工作表单元格的值。 However when I checked the values in the immediate window, they are not match with the real values at all. 但是,当我在即时窗口中检查值时,它们根本与实际值不匹配。 Some are null. 有些为空。 Why? 为什么? Thanks for advice. 谢谢你的建议。

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

Try this... pass the file path and the worksheet name then parse the datatable as you like in simple way or LINQ way 试试这个...传递文件路径和工作表名称,然后按照您喜欢的简单方式或LINQ方式解析数据表

I believe that culprit would be below line: 我相信罪魁祸首将在下面:

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

This will collapse your range to just one cell - you can quickly test that by checking xlRange.Rows.Count. 这会将您的范围缩小到一个单元格-您可以通过检查xlRange.Rows.Count来快速进行测试。 I will suggest that you remove this line and code should work. 我建议您删除这一行,代码应该可以工作。 Another trick that you may find useful is Range.Value property will return array of values if range has multiple cells. 您可能会发现有用的另一个技巧是Range.Value属性,如果range有多个单元格,它将返回值的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM