简体   繁体   English

从 ExcelDataReader 数据集中保存值

[英]Saving Values from ExcelDataReader DataSets

I'm using C# to read an Excel file using ExcelDataReader and ExcelDataReader.DataSet .我正在使用 C# 使用ExcelDataReaderExcelDataReader.DataSet读取 Excel 文件。 I'm not too familiar with parsing DataSets so I was wondering how to save the values from each row in a particular column in the Excel.我对解析数据集不太熟悉,所以我想知道如何将每一行的值保存在 Excel 的特定列中。 I need the code to pull all the values from the first column of the spreadsheet I load.我需要代码从我加载的电子表格的第一列中提取所有值。

public void ExcelFileReader(string path)
{
    var stream = File.Open(path, FileMode.Open, FileAccess.Read);
    var reader = ExcelReaderFactory.CreateReader(stream);
    var rowCount = reader.RowCount;

    result = reader.AsDataSet(new ExcelDataSetConfiguration()
    {
        ConfigureDataTable = (DataTableReader) => new ExcelDataTableConfiguration()
        {
            UseHeaderRow = true
        }
    });

    var tables = result.Tables.Cast<DataTable>();
    var dataTable = result.Tables[0].Columns[0].ToString();
    foreach(DataTable table in tables)
    {
        dataGridView1.DataSource = table;
    }
}

The line: var dataTable = result.Tables[0].Columns[0].ToString();该行: var dataTable = result.Tables[0].Columns[0].ToString(); will get me the name of the header for the column I want but how do I parse through the rows of column 1 and save all the values?会给我我想要的列的标题名称,但是如何解析第 1 列的行并保存所有值?

You have to iterate throught the rows of the table and then get the column 0 value.您必须遍历表的行,然后获取第 0 列的值。

foreach (DataRow row in dataset.Tables[0].Rows)
{
    Console.WriteLine(row[0]);
}

This will write all the values from the first column (index 0).这将写入第一列(索引 0)中的所有值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM