将Excel中列中的某些单元格导入到c#

本文关键字:单元格 导入 Excel | 更新日期: 2023-09-27 18:09:01

我的excel文件是column1A:城市,安卡拉,安卡拉,安卡拉,伊斯坦布尔,伊斯坦布尔,伊兹密尔我想那个组合框看起来像安卡拉,伊斯坦布尔,伊兹密尔又没了。

OleDbConnection baglan = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0");    
baglan.Open();    
string sql = "Select * From [Sayfa1$A1:A100] ";    
OleDbCommand komut = new OleDbCommand(sql, baglan);    
OleDbDataReader dr = null;    
dr = komut.ExecuteReader();    
while (dr.Read())
{    
   if (dr[0] != "")
   {    
        combobox1.Items.Add(dr[0].ToString());    
   }    
   else    
   {    
       break;   
   }    
}   
baglan.Close();

将Excel中列中的某些单元格导入到c#

if (dr[0] != ""){   
   if(!combobox1.Items.Contains(dr[0])){
    combobox1.Items.Add(dr[0].ToString());
   }
}

试试这个:

    OleDbConnection baglan = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0");    
baglan.Open();    
string sql = "Select * From [Sayfa1$A1:A100] ";    
OleDbCommand komut = new OleDbCommand(sql, baglan);    
OleDbDataReader dr = null;    
dr = komut.ExecuteReader();
                DataTable dt = new DataTable();
            dt.Load(dr);
     // To Copy distinct values from specified column to a different datatable
    DataTable diffValues = dt.DefaultView.ToTable(true, "ColName");
    combobox1.DataSource = datatable;