【问题标题】:Read excel spreadsheet into a datatable将excel电子表格读入数据表
【发布时间】:2017-07-21 05:48:45
【问题描述】:

我在我的程序中使用以下 C# 代码使用 oledbconnection 将 excel 97 - 2003 电子表格数据读取到数据表中,并遇到当前上下文中不存在的名称。

DataTable rs = null;

string path = Path.GetFullPath(filePath);
odConnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
odConnection.Open();
OleDbCommand cmd = new OleDbCommand(); ;
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
DataTable dt = odConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = string.Empty;
if (dt != null)
{
    sheetName = dt.Rows[0]["Sheet_Name"].ToString();
}

cmd.Connection = odConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
oda = new OleDbDataAdapter(cmd);
oda.Fill(ds, "excelData");
rs = ds.Tables["excelData"];

【问题讨论】:

  • 添加更多详细信息。例外,行,你的 excel 有哪些工作表
  • 第 3 行,名称 odConnection 在当前上下文中不存在。
  • 你没有声明 odConnection 所以它不存在。例如,尝试在odConnection 之前添加var
  • @SamvelPetrosov 谢谢,有没有办法过滤一个特定的电子表格而不是循环所有。我有 12 张不同的工作表,而我只对一张电子表格感兴趣。
  • 看看我的回答

标签: c# excel


【解决方案1】:

这里是如何从 xlsx 文件的特殊工作表中获取所有列和行的示例。此代码从 xlsx 文件中获取来自 Sheet2 的所有数据,并使用该值填充 DataTable。

希望这会对你有所帮助。

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

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable rs = new DataTable();

            using (var odConnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\Users\IIG\Desktop\test.xlsx;Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"))
            {
                odConnection.Open();

                using (OleDbCommand cmd = new OleDbCommand())
                {
                    cmd.Connection = odConnection;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "SELECT * FROM [Sheet2$]";
                    using (OleDbDataAdapter oleda = new OleDbDataAdapter(cmd))
                    {
                        oleda.Fill(rs);
                    }
                }
                odConnection.Close();
            }
            foreach(DataRow row in rs.Rows)
            {
                foreach(object item in row.ItemArray)
                {
                    Console.Write(item +"\t");
                }
                Console.WriteLine();
            }
        }
    }
}

【讨论】:

  • 非常感谢。这有帮助
【解决方案2】:

下一行可能导致问题 -

if (dt != null)
    {
        sheetName = dt.Rows[0]["Sheet_Name"].ToString();
    }

尝试使用

dt.Rows[0]["Table_name"].ToString(); 

这应该返回工作表的名称。

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多