【问题标题】:Excel Sheets into multiple C# datatables将 Excel 表格转换为多个 C# 数据表
【发布时间】:2014-11-15 03:04:38
【问题描述】:

我正在尝试将 Excel 电子表格导入到数据表数组中。每个表都是电子表格中的一张表。现在我看到每个表都包含来自所有工作表的信息。我认为这部分工作不正常。

dataSet.Clear();

如果你能看出我做错了什么,请告诉我。

这是其余的代码。

        public DataTable[] ReadDoc()
        {
        string filename = @"C:\Documents and Settings\user\Desktop\Test.xlsx";
        DataTable dt = null;

        string connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\";", filename);
        OleDbConnection connection = new OleDbConnection(connectionString);

        DataSet dataSet = new DataSet();
        DataSet finalDataSet = new DataSet();
        DataTable[] table = new DataTable[3];
        connection.Open();

        dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        if (dt == null)
        {
            return null;
        }

        String[] excelSheets = new String[dt.Rows.Count];
        int i = 0;

        foreach (DataRow row in dt.Rows)
        {
            excelSheets[i] = row["TABLE_NAME"].ToString();
            i++;
        }

        // Loop through all of the sheets if you want too...
        for (int j = 0; j < excelSheets.Length; j++)
        {
            string query = String.Format("SELECT * FROM [" + excelSheets[j] + "]");
            dataSet.Clear();
            OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
            dataAdapter.Fill(dataSet);
            table[j] = dataSet.Tables[0];
        }

        return table;
        }

感谢您的帮助。

【问题讨论】:

    标签: c# excel datatable


    【解决方案1】:

    这里的问题是你的数据集,被声明为超出了 for。每个数据表数组项都获得相同的信息。数据集.表[0];您必须在 for 中声明。每次迭代存储不同的信息。

     for (int j = 0; j < excelSheets.Length; j++)
        {
            DataSet dataSet = new DataSet();
            string query = String.Format("SELECT * FROM [" + excelSheets[j] + "]");
            .....
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 2020-08-30
      • 2011-03-18
      • 1970-01-01
      相关资源
      最近更新 更多