3

更新 2

string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", EXCELFILENAME);

            string testCaseName = "test_case_2";

            string query = String.Format("SELECT * from [{0}$] WHERE columns={1}", workbookName, testCaseName);

            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);

            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet); //<<ERROR 

        DataTable myTable = dataSet.Tables[0]; 

错误:没有为一个或多个必需参数指定值。

更新结束

更新:

string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", EXCELFILENAME);
            string query = String.Format("select * from [{0}$]", workbookName);

            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);               
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);

            DataTable myTable = dataSet.Tables[0];

如何从单元格中读取数据并将其存储在数组/字符串中。我已经阅读了工作表,但找不到更好的方法

所以这是我的 excel 表的样子:

在此处输入图像描述

我应该能够通过我的案例 test_case_1 或 test_case_2 等中的列...并读取该特定行的列...。

4

3 回答 3

2

我建议你看看LinqToExcel。它使在 .NET 中查询 Excel 变得非常容易。

var book = new LinqToExcel.ExcelQueryFactory(@"E:\Temporary\Workbook.xlsx");

var current_test_case = "Test_case_1";

var query =
    from row in book.Worksheet("Sheet1")
    let columns = row["columns"].Cast<string>()
    where columns == current_test_case
    select new
    {
        id = row["id"].Cast<int>(),
        name = row["name"].Cast<string>(),
        caption = row["caption"].Cast<string>(),
        date = row["date"].Cast<DateTime>(),
        success = row["success"].Cast<bool>(),
    };
于 2012-08-30T03:40:01.147 回答
0

嗨,Abu Hamzah,作为您的要求只读必填列,代码在这里,它是一个用于读取 excel 数据的 consol 应用程序

class Program
{
    internal static ILog logger = LogManager.GetLogger(typeof(Program));
    static void Main(string[] args)
    {
        log4net.Config.XmlConfigurator.Configure();
        string firstName, lastName, dob, lexisNexisID;
        string filePath = @"yor directory path\your file name";

        ExcelProvider provider = ExcelProvider.Create(filePath, "Sheet1");
        foreach (ExcelRow row in (from x in provider select x))
        {
            Console.WriteLine("{0}", row.GetString(1));
            /* the row.Getstring(index) the index is for your column you mey select morcolume as Console.WriteLine("{0}/t{1}", row.GetString(0),row.Getstring(1)); */
        }

    }

}

public class ExcelRow
{
    List<object> columns;

    public ExcelRow()
    {
        columns = new List<object>();
    }

    internal void AddColumn(object value)
    {
        columns.Add(value);
    }

    public object this[int index]
    {
        get { return columns[index]; }
    }

    public string GetString(int index)
    {
        if (columns[index] is DBNull)
        {
            return null;
        }
        return columns[index].ToString();
    }

    public int Count
    {
        get { return this.columns.Count; }
    }
}

public class ExcelProvider : IEnumerable<ExcelRow>
{
    private string sheet;
    private string filePath;
    private List<ExcelRow> rows;


    public ExcelProvider()
    {
        rows = new List<ExcelRow>();
    }

    public static ExcelProvider Create(string filePath, string sheet)
    {
        ExcelProvider provider = new ExcelProvider();
        provider.sheet = sheet;
        provider.filePath = filePath;
        return provider;
    }

    private void Load()
    {
        string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=    ""Excel 12.0;HDR=YES;""";
        connectionString = string.Format(connectionString, filePath);
        rows.Clear();
        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            try
            {
                conn.Open();
            }
            catch (Exception ex)
            {
            }
            using (OleDbCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = "select * from [" + sheet + "$]";
                using (OleDbDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        ExcelRow newRow = new ExcelRow();
                        for (int count = 0; count < reader.FieldCount; count++)
                        {
                            newRow.AddColumn(reader[count]);
                        }
                        rows.Add(newRow);
                    }
                }
            }
        }
    }

    public IEnumerator<ExcelRow> GetEnumerator()
    {
        Load();
        return rows.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        Load();
        return rows.GetEnumerator();
    }

}
于 2012-08-30T03:57:34.230 回答
0

关于过滤。

当您使用 OleDb 进行数据检索时,没有什么可以阻止您使用更高级的 SQL:

string testCaseName = "Test_case_1
string query = String.Format("SELECT * from [{0}$] WHERE columns=\"{1}\"", workbookName, testCaseName);

您可以使用列的名称进行过滤。在您的情况下,过滤器位于字段上。(顺便说一句。这是一个令人困惑的名字)

据我记得表格的标题必须在第一行,您可能需要将表格向上移动一行。

于 2012-08-30T09:34:15.487 回答