1. 程式人生 > >根據EXCEL單元range生成select語句(考慮重複項)

根據EXCEL單元range生成select語句(考慮重複項)

        public void Test(IRibbonControl control)
        {
            Excel.Application app = ExcelDnaUtil.Application as Excel.Application;
            Excel.Worksheet sht = app.ActiveSheet as Excel.Worksheet;

            Excel.Range rng = null;
            rng = app.Selection;

            //List<string> ls = new List<string>();
            List<string> ls1 = new List<string>();
            int num = 0;
            foreach (Excel.Range r in rng)
            {
                object o = r.Value;
                if (null != o)
                {
                    string fieldName = MyCommon.GetPinYinFirstLetter(o.ToString());
                    int count = CountElements(fieldName, ls1);
                    if (0 != count)
                        ls1.Add(string.Format("{0} AS {1}",fieldName,fieldName+count.ToString()));
                    else
                        ls1.Add(fieldName);

                    //ls.Add(string.Format("{0} as [{1}]", MyCommon.GetPinYinFirstLetter(o.ToString()), o.ToString()));
                }
                else {
                    ls1.Add(string.Format("{0} as [{1}]", "''", ++num));
                    //ls.Add(string.Format("{0} as [{1}]","''",++num));
                }
            }
            //string msg = string.Join(",",ls.ToArray());
            //MyCommon.WriteLog(msg);
            MyCommon.WriteLog(string.Join(",",ls1.ToArray()));

            //MessageBox.Show(msg);
        }

        private int CountElements(string ele, List<string> ls) {
            int count = 0;
            if (string.IsNullOrEmpty(ele))
                return count;

            foreach (string item in ls)
            {
                if (item.Split(' ')[0].Equals(ele))
                    count++;
            }
            return count;
        }