3

我想知道如何在 c# 中读取多个具有不同工作表名称的 Excel 工作表并使用 oledb。

我有这种现有的方式来阅读多张工作表(但具有固定的工作表名称):

DataSet ds = new DataSet();
var excelConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0", path); 
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = excelConnectionString;

var i = 1;
while (i <= 4)
{
    string query = "SELECT * FROM [Sheet" + i + "$]";
    ds.Clear();
    OleDbDataAdapter data = new OleDbDataAdapter(query, connection);
    data.Fill(ds);

    // other stuff
    i = i + 1;
}

这个有效。但我现在处于工作表名称不固定的不同情况,例如:Sheet1 是 Dog,Sheet2 是 Cat Sheet3 是 Bird。

现在我关心的是如何使用现有代码循环这些工作表名称。

4

2 回答 2

4

这是来自 VB.net 但不确定它的翻译效果如何,返回包含所有工作表名称的字符串列表:

OleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})

MSDN 链接

获得工作表名称列表后,您可以执行简单的For Each循环进行迭代。

编辑:

这应该在 C# 中工作

添加功能

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

您的代码将更改为:

DataSet ds = new DataSet();
var excelConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0", path); 
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = excelConnectionString;

DataTable sheets = GetSchemaTable(excelConnectionString);

foreach (dataRow r in sheets.rows)
{
    string query = "SELECT * FROM [" + r.Item(0).ToString + "]";
    ds.Clear();
    OleDbDataAdapter data = new OleDbDataAdapter(query, connection);
    data.Fill(ds);

}

ds只要确保在每次迭代后做一些事情。

于 2013-09-03T12:42:13.957 回答
0

我使用下面的代码,它适用于我在一个 excel 文件中的不同工作表。

using (SpreadsheetDocument doc = SpreadsheetDocument.Open(ratesFilePath, false))
{
    WorkbookPart workbookPart = doc.WorkbookPart;
    Sheets sheets = workbookPart.Workbook.GetFirstChild<Sheets>();
    foreach (Sheet sheet in sheets)
    {
        if (sheet.Name == "Sheet Name")
        {
            Worksheet worksheet = ((WorksheetPart)workbookPart.GetPartById(sheet.Id)).Worksheet;
            SheetData sheetData = (SheetData)worksheet.GetFirstChild<SheetData>();
            foreach (Row row in sheetData)
            {

                if ((row.FirstChild as Cell).CellReference.ToString().Contains("A") && (row.FirstChild as Cell).CellValue != null && row.RowIndex != 1)
                {
                    RateInformation RateInformationElement = new RateInformation();
                    foreach (Cell c in row)
                    {
                        string cellValue = null;
                        if ((c.DataType != null) && (c.DataType == CellValues.SharedString))
                        {
                            int id = -1;
                            if (Int32.TryParse(c.InnerText, out id))
                            {
                                SharedStringItem item = GetSharedStringItemById(workbookPart, id);
                                if (item.Text != null)
                                {
                                    //code to take the string value
                                    cellValue = item.Text.Text;
                                }
                                else if (item.InnerText != null)
                                {
                                    if (Convert.ToDouble(item.InnerText).ToString() != null)
                                    {
                                        cellValue = Convert.ToDouble(item.InnerText).ToString();
                                    }
                                    else 
                                    { 
                                        cellValue = item.InnerText;
                                    }
                                }
                                else if (item.InnerXml != null)
                                {
                                    cellValue = item.InnerXml;
                                }
                            }
                        }
                        else
                        {
                            cellValue = c.InnerText;
                        }
                        if (c.CellReference.ToString().Contains("A"))
                        {
                            RateInformationElement.Unit = cellValue;
                        }
                        else if (c.CellReference.ToString().Contains("B"))
                        {
                            Decimal.TryParse(cellValue, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal result);
                            RateInformationElement.Price = Convert.ToDecimal(result);
                        }
                    }
                    rateInformations.Add(RateInformationElement);
                }
            }
        }
    }
}
于 2022-01-19T08:05:11.097 回答