简体   繁体   English

读取Excel文件的特定列并使用C#添加到查询

[英]read particular column of excel file and add to query using c#

I want to read a particular column from an excel file and pick each value and put it into a query using c#. 我想从Excel文件中读取特定列,并选择每个值并将其放入使用C#的查询中。 I have written a code to read an excel file and show it in datagridview but got stuck while reading a particular column. 我已经编写了一个代码来读取Excel文件并在datagridview中显示它,但是在读取特定列时卡住了。

Need some help. 需要一些帮助。 Below is the code. 下面是代码。

private void button1_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xls", ValidateNames = true })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
            IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(fs);
            var conf = new ExcelDataSetConfiguration
            {
                ConfigureDataTable = _ => new ExcelDataTableConfiguration
                {
                    UseHeaderRow = true
                }
            };
            dataSet = reader.AsDataSet(conf);
            cboSheet.Items.Clear();
            foreach (DataTable dt in dataSet.Tables)
                cboSheet.Items.Add(dt.TableName);
            reader.Close();
        }
    }
}

private void cboSheet_SelectedIndexChanged(object sender, EventArgs e)
{
    dataGridView.DataSource = dataSet.Tables[cboSheet.SelectedIndex];
}

Do you know the excel file will be the same each time? 您知道excel文件每次都相同吗? If you can ensure the file will be consistently the same without any column modifications, you can do the following with OfficeOpenXml package. 如果可以确保文件在没有任何列修改的情况下保持一致,则可以使用OfficeOpenXml软件包执行以下OfficeOpenXml

public IEnumerable<string> ReadFile(string path)
{
     using(var file = new FileStream(path, FileMode.Open))
     using(var memory = new MemoryStream())
     {
          file.CopyTo(memory);
          using(var package = new ExcelPackage(memory))
               if(package.Workbook.Worksheets.Count != 0)
                    foreach(ExcelWorksheet worksheet in package.Workbook.Worksheets)
                         for(var row = 0; worksheet.Dimension.Start.Row; row <= worksheet.Dimension.End.Row; row++)
                              yield return worksheet.Cells[row, 2].Value;
     }
}

For brevity I didn't abstract, you could make the code a bit more clear by separating the multiple loop, for worksheet then the rows. 为简便起见,我没有抽象化,您可以通过将多个循环分开来简化代码,首先是工作表,然后是行。 As you can see the "2" is representing the specified column. 如您所见,“ 2”代表指定的列。 But that would give you a collection you could iterate to dump into your query to process. 但这将为您提供一个集合,您可以迭代将其转储到查询中以进行处理。

You can use ExcelDataReader , that will give you the entire excel content as DataTable 您可以使用ExcelDataReader ,它将为您提供整个Excel内容作为DataTable

Or you can use OleDbCommand 或者您可以使用OleDbCommand

    OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelPath + "; Extended Properties = 'Excel 12.0;HDR=YES;';");

    conn.Open();

    OleDbCommand cmd = new OleDbCommand();

    cmd.Connection = conn;

    cmd.CommandText = SELECT [Colum1], [Colum2] FROM [Sheet1$];

    OleDbDataReader reader =  cmd.ExecuteReader();

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

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