使用ExcelDataReader时如何将多个Excel工作表作为数据表传递?

时间:2018-07-12 10:11:21

标签: c# excel datatable exceldatareader

我想知道如何在下面的代码中传递多个“工作表”吗?
我正在使用Selenium C#在Web应用程序中填写一些数据,在其中填写“ Sheet1”上的信息时,我必须继续填写“ Sheet2”中的信息。下面的代码仅在“ Sheet 1”中传递。我该如何增强它以便可以在那里获得多张纸?

public DataTable ExcelToDataTable(string filename)    
{
    FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read);
    IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

    DataSet result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
    {
        ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
        {
            UseHeaderRow = true
        }
    });

    DataTableCollection table = result.Tables;
    DataTable resultTable = table["sheet1"]; //here I'd like to have more than just one "sheet"

    return resultTable;    
}

2 个答案:

答案 0 :(得分:0)

假设最后三行代码可以与此交换:

curl -I https://example.com/file.pdf

来源:How to combine two DataSet Tables into one

答案 1 :(得分:0)

当您有一个包含多个工作表的Excel工作簿时,您希望分别使用每个工作表,我建议您使用Singleton设计模式来存储Excel工作簿的信息-使用适当的数据/查询模型-然后读取数据从那个单例实例开始。

例如:

yourTableView.estimatedRowHeight = 70.0 // this can be any height you want to set when table loads first time.
yourTableView.rowHeight = UITableViewAutomaticDimension

然后您可以使用Excel工作表,如下所示:

// singleton object of 
public class ExcelDataContext
{
    // creating an object of ExcelDataContext
    private static ExcelDataContext instance = new ExcelDataContext();

    // no instantiated available
    private ExcelDataContext()
    {
        FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

        DataSet result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
        {
            ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
            {
                UseHeaderRow = true
            }
        });

        this.Sheets = result .Tables;
    }

    // accessing to ExcelDataContext singleton
    public static ExcelDataContext GetInstance()
    {
        return instance;
    }

    // the dataset of Excel
    public DataTableCollection Sheets { get; private set; }
}

以及当您需要读取另一张纸的数据时:

DataTable sheet1 = ExcelDataContext.GetInstance().Sheets["sheet1"];

那将不再阅读Excel工作簿。