c# - 使用 c# 在单个 xlsx 中读取多个 Excel 工作表

标签 c# excel

这个问题在这里已经有了答案:





Reading multiple excel sheets with different worksheet names

(2 个回答)


7年前关闭。




使用 c# 我可以成功打开一个 excel 文档并使用下面的代码读取第一个工作表中的数据。但是,我的 .xlsx 有多个工作表,所以我想遍历工作表集合,而不是硬编码每个工作表的名称。非常感谢。

       string path = @"C:\Extract\Extract.xlsx";
       string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";

       string sql = "SELECT * FROM [Sheet1$]";

       using (OleDbDataAdapter adaptor = new OleDbDataAdapter(sql, connStr))
       {
           DataSet ds = new DataSet();
           adaptor.Fill(ds);

           DataTable dt = ds.Tables[0];
       }

最佳答案

我在这里的答案中使用了大部分代码 [ Reading multiple excel sheets with different worksheet names在对我的问题的评论中向我指出了这一点。
它不会在 VS 2013 中为我编译,因为 DataRow 对象没有属性 Item(- r.Item(0).ToString 在该代码中)。所以我只是改变了一点。它还带回了一些名称中包含 Print_Area 无效的工作表,因此我将其从循环中删除。这是对我有用的代码。

       string path = @"C:\Extract\Extract.xlsx";
       string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";

       DataTable sheets = GetSchemaTable(connStr);

       string sql = string.Empty;
       DataSet ds = new DataSet();
       foreach (DataRow dr in sheets.Rows)
       {  //Print_Area
           string WorkSheetName = dr["TABLE_NAME"].ToString().Trim();

           if (!WorkSheetName.Contains("Print_Area"))
           {
               sql = "SELECT * FROM [" + WorkSheetName + "]";
               ds.Clear();
               OleDbDataAdapter data = new OleDbDataAdapter(sql, connStr);
               data.Fill(ds);

               DataTable dt1 = ds.Tables[0];

               foreach (DataRow dr1 in dt1.Rows)
               {
                   //parsing work
               }
           }
       }

    static DataTable GetSchemaTable(string connectionString)
    {
        using (OleDbConnection connection = new
                   OleDbConnection(connectionString))
        {
            connection.Open();
            DataTable schemaTable = connection.GetOleDbSchemaTable(
                OleDbSchemaGuid.Tables,
                new object[] { null, null, null, "TABLE" });
            return schemaTable;
        }
    }

关于c# - 使用 c# 在单个 xlsx 中读取多个 Excel 工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26422671/

相关文章:

c# - 在 C# 或 JavaScript 中将 DIV 内容转换为图像

c# - 如何处理ServiceStack中的多个服务?

c# - 如何在 c# 应用程序中两次调用 Web 服务之间保持 session 事件?

vba - 我的 IF/ELSE IF 语句在 VBA 中不起作用

表单组合框上的 Excel VBA 循环单元格链接

r - 如何使用 R 读取合并的 Excel 单元格

c# - ASP.NET核心: Parse complex struct from URL

c# - WPF ComboBox : Trouble converting back-and-forth of Selected Item (Works in all cases, 但就是这个。)

python - 使用 Openpyxl 打开文件夹中的文件

excel - 使用范围的最后一列(F :LastColumn)