zoukankan      html  css  js  c++  java
  • 项目中常用方法总结(将将DataTable数据集映射到实体对象)【转】

    本篇把项目中用到的一些通用方法总结出来, 这些方法因为经常需要在项目中用到,所以把它们归纳在一起, 形成一个.dll 文件是一个理想的选择. 这样也便于日后缩短开发周期.
     
    一. 把一个DataGridView对象转换成一个DataTable对象
     public static DataTable GetDgvToTable(DataGridView dgv)
       {

               if(dgv==null) throw new NullReferenceException();
                DataTable dt = new DataTable();
                for (int count = 0; count < dgv.Columns.Count; count++)  //遍历DataGridView每一列
                {
                    DataColumn _column = new DataColumn(dgv.Columns[count].Name.ToString()); //根据DataGridView每一列创建一个列对象
                    dt.Columns.Add(_column); //添加列
                }  

               for (int count = 0; count < dgv.Rows.Count; count++)    //遍历DataGridView没一行
                {
                    DataRow dr = dt.NewRow();
                    for (int col = 0; col < dgv.Columns.Count; col++)
                    {
                        dr[col] = dgv.Rows[count].Cells[col].Value == null ? "" : dgv.Rows[count].Cells[col].Value.ToString();
                    }
                    dt.Rows.Add(dr); //添加行
                }
                return dt;
            }

     
    2. 给DataTable添加合计行
     public static DataTable AddCountRow(DataTable dt, int[] index)
         {
                if (dt.Rows.Count > 0)
                {
                    DataRow row = dt.NewRow();
                    row[0] = "合计:";
                    row[1] = dt.Rows.Count + "";
                    for (int i = 0; i < index.Length; i++) //遍历需要合计的行

                    {
                        for (int j = 0; j < dt.Columns.Count; j++) //遍历DataTable每一列
                        {
                            int columnIndex = 0;
                            if (index == j) //找到第一个要合计的列
                            {
                                columnIndex = index; //合计列索引
                                string columname = dt.Columns[columnIndex].ColumnName; //要合计列的名称
                                if (string.IsNullOrEmpty(dt.Compute("sum(" + columname + ")", "true").ToString())) //判断是否为空
                                    row[columnIndex] = 0.00;
                                else
                                    row[columnIndex] = decimal.Parse(dt.Compute("sum(" + columname + ")", "true").ToString());  //得到合计列的结果
                                break;
                            }
                        }
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

     
    3. 将DataTable数据集映射到实体对象
      public static List<TResult> TableToObject<TResult>(DataTable dt, TResult ob) //泛型方法,此处TResult为类型参数
            {
                List<PropertyInfo> prlist = new List<PropertyInfo>();//创建一个属性列表集合


                Type t = typeof(TResult); //获取实体对象的元数据Type类型


                PropertyInfo[] prArr = t.GetProperties(); //取得实体对象的所有属性到属性集合中

                foreach (PropertyInfo pr in prArr) //循环遍历属性集合到List集合
                    prlist.Add(pr);
                //通过匿名方法自定义筛选条件  => 检查datatable中是否存在存在此列, 

                Predicate<PropertyInfo> prPredicate = delegate(PropertyInfo pr) { if (dt.Columns.IndexOf(pr.Name) != -1) return true; return false; };
                //从指定的条件中

               List<PropertyInfo> templist = prlist.FindAll(prPredicate);
               //创建一个实体集合
                List<TResult> oblist = new List<TResult>();
               //遍历DataTable每一行
                foreach (DataRow row in dt.Rows)
                {
                    ob = (TResult)Activator.CreateInstance(t);  //通过Type类型创建对象,并强制转换成实体类型

                    Action<PropertyInfo> prAction = delegate(PropertyInfo pr) {if(row[pr.Name] != DBNull.Value) pr.SetValue(ob, row[pr.Name], null); };
                     //把选择出来的属性集合的每一个属性设置成上面创建的对象的属性

                    templist.ForEach(prAction);
                    oblist.Add(ob); //把属性添加到实体集合
                }
                return oblist;
            }

     
    4. 将一个DataTable导出到Excel中
    // 参数依次为报表标题, 数据集
     public static void ExportExcel(string p_ReportName, DataTable dt)
            {

                string saveFileName = "";
                bool fileSaved = false;
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.DefaultExt = "xls";
                saveDialog.Filter = "Excel文件|*.xls";
                saveDialog.FileName = "Sheet1";
                saveDialog.ShowDialog();

                saveFileName = saveDialog.FileName;
                if (saveFileName.IndexOf(":") < 0) return; //被点了取消 


                // 创建Excel对象                   
                Excel.Application xlApp = new Excel.ApplicationClass();
                if (xlApp == null)
                {
                    MessageBox.Show("Excel无法启动");
                    return;
                }
                // 创建Excel工作薄
                Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
                Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets[1];

                // 设置标题
                Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, dt.Columns.Count]);
                //Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, m_dt.Columns.Count]);
                range.MergeCells = true;
                xlApp.ActiveCell.FormulaR1C1 = p_ReportName;
                xlApp.ActiveCell.Font.Size = 20;
                xlApp.ActiveCell.Font.Bold = true;
                xlApp.ActiveCell.HorizontalAlignment = Excel.Constants.xlCenter;

                // 列索引,行索引,总列数,总行数
                int colIndex = 0;
                int RowIndex = 0;
                int colCount = dt.Columns.Count;
                int RowCount = dt.Rows.Count - 1;//this.BindingContext[this.DataSource, this.DataMember].Count;

                // 创建缓存数据
                object[,] objData = new object[RowCount + 1, colCount];

                // 获取列标题
                foreach (DataColumn cs in dt.Columns)
                {
                    objData[RowIndex, colIndex++] = cs.ColumnName;
                }
                // 获取数据
                for (RowIndex = 1; RowIndex < RowCount; RowIndex++)
                {
                    for (colIndex = 0; colIndex < colCount; colIndex++)
                    {
                        objData[RowIndex, colIndex] = dt.Rows[RowIndex][colIndex];//this[RowIndex - 1, colIndex];
                    }
                    Application.DoEvents();
                }
                // 写入Excel
                range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, colCount]);
                range.Value2 = objData;

                // 保存
                try
                {
                    xlBook.Saved = true;
                    xlBook.SaveCopyAs(saveFileName);
                    MessageBox.Show("导出成功!");
                }
                catch
                {
                    MessageBox.Show("保存出错,请检查!");
                    return;
                }
                finally
                {
                    xlApp.Quit();
                    GC.Collect();
                }
                return;
            }

    5. 通过字典缓存一些不变的本地数据集
    //声明一个字典集合
      private static Dictionary<string, object> dicObject = new Dictionary<string, object>();
    //下面缓存某个数据集
      public static DataTable GetCustomers(string custup)
            {
                DataTable dt;
                string key = "AllCustomers" + custup;
                if (dicObject.ContainsKey(key))
                {
                    dt = (DataTable)dicObject[key];
                }
                else
                {
                    dt = BasicInfo.GetCustomers(custup).Tables[0];
                    dicObject.Add(key, dt);
                }
                return dt;
            }

  • 相关阅读:
    Excel 相对引用与绝对引用
    SQL Update 巧用
    Delphi 多步操作产生错误,请检查每一步的状态值
    cxGrid 增加序号 (非数据库绑定模式) (测试通过)
    delphi cxgrid 使用方法
    如何使满足条件的数据显示不同的颜色
    Delphi中Format与FormatDateTime函数详解
    常用的日期时间函数
    100m和1000m网线的常见制作方法
    基于请求的分布式互斥算法
  • 原文地址:https://www.cnblogs.com/zhouyunbaosujina/p/3154817.html
Copyright © 2011-2022 走看看