EXCEL datatable 根据列名自动写入到相应属性、字段或列中

string path = openFileDialog1.FileName;
                try
                {
                    DataTable dt = ExcelHelper.ExcelInput(path);

                    int appidIndex = -1;
                    int shopidIndex = -1;
                    int storeidIndex = -1;


                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string colNmaeL = dt.Columns[i].ColumnName.ToLower();
                        if (colNmaeL.Contains("app") && colNmaeL.Contains("id"))
                            appidIndex = i;

                        if (colNmaeL.Contains("shop") && colNmaeL.Contains("id"))
                            shopidIndex = i;

                        if (colNmaeL.Contains("store") && colNmaeL.Contains("id"))
                            storeidIndex = i;
                    }

                    List<SHOPID> lstShopids = new List<SHOPID>();

                    string firstAppId = string.Empty;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        DataRow dr = dt.Rows[i];
                        SHOPID si = new SHOPID();
                        if(dr[appidIndex]!=null&&!string.IsNullOrEmpty(dr[appidIndex].ToString()))
                            firstAppId = dr[appidIndex].ToString();
                        si.appid = firstAppId;

                        si.storeid = dr[storeidIndex].ToString();
                        si.shopid = dr[shopidIndex].ToString();

                        lstShopids.Add(si);
                    }

                    dataGridView1.DataSource = lstShopids;

                    MessageBox.Show("abc");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

-

原文地址:https://www.cnblogs.com/runliuv/p/6028031.html