项目中常用方法总结(将将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;
}
项目中常用方法总结(将将DataTable数据集映射到实体对象)【转】的更多相关文章
- 为什么在项目中data需要使用return返回数据呢?
问:为什么在项目中data需要使用return返回数据呢? 答:不使用return包裹的数据会在项目的全局可见,会造成变量污染:使用return包裹后数据中变量只在当前组件中生效,不会影响其他组件.
- 导出Excel文件(项目中会遇到很多将一些数据导出Excel或者et)
最近在项目中,遇到一些需求,就是将数据导出来,以Excel文件为主:就自己简单的做一些demo:供初学者来学习: // 定义一个保存文件的路径位置 SaveFileDialog dlgPath = n ...
- 一个Web项目中实现多个数据库存储数据并相互切换用过吗?
最近公司一个项目需要连接多个数据库(A和B)操作,根据不同的业务模块查询不同的数据库,因此需要改造下之前的spring-mybatis.xml配置文件以及jdbc.properties配置文件,项目后 ...
- 项目中整合第三方插件与SpringMVC数据格式化关于ip地址
一.Bootstrap 响应式按钮 <div calss="col-sm-2"> <button class="btn btn-default btn- ...
- 项目中简单使用ztree,简单数据。
由于公司架构较旧,使用的jdk版本为1.4,页面上也没有el表达式. 加入 js 文件 <% String context = request.getContextPath(); %> & ...
- vue项目中使用mockjs+axios模拟后台数据返回
自己写练手项目的时候常常会遇到一个问题,没有后台接口,获取数据总是很麻烦,于是在网上找了下,发现一个挺好用的模拟后台接口数据的工具:mockjs.现在把自己在项目中使用的方法贴出来 先看下项目的目 ...
- 关于Servo项目中Rust代码行数的数据来源
我两个月之前的一篇博客<为什么我说Rust是靠谱的编程语言>(下面简称原文),在当中"6. 两个半大型成功案例"一节.我以前写道: Servo: 下一代浏览器渲染引擎( ...
- MongoDB项目中常用方法
使用MongoDB连接池MongoOptions来进行连接 以及相关方法的调用 //获得驱动地址(这里的驱动 写入了配置文件中) String serverAddressStr = Configure ...
- vue项目中使用mockjs模拟接口返回数据
Mock.js 是一个模拟数据生成器,利用它,可以拦截ajax请求,直接模拟返回数据,这样前后端只要约定好数据格式,前端就不需要依赖后端的接口,可以直接使用模拟的数据了. 网上介绍mock的教程也较多 ...
随机推荐
- java没有条件编译
摘自http://maosidiaoxian.iteye.com/blog/1290740 条件编译绝对是一个好东西.如在C或CPP中,可以通过预处理语句来实现条件编译.代码如下: #IFDEF DE ...
- Timer和TimerTask
目录结构: Timer和TimerTask 一个Timer调度的例子 如何终止Timer线程 关于cancle方式终止线程 反复执行一个任务 schedule VS. scheduleAtFixedR ...
- linux 在批处理中,完整路径有空格的处理方式(加引號)
cp -f E:/XML_EDITOR/xmleditor25/xmleditor/Editor_UIOuterCtrl/TraceViewDlg.cpp E:/XML_EDITOR/'XMLEdit ...
- Android 官方文档:(二)应用清单 —— 2.26 <uses-permission>标签
syntax: <uses-permission android:name="string" android:maxSdkVersion="inte ...
- svn 清理失败 (cleanup 失败) 的解决方法
svn 清理失败 (clean up 失败) 的解决方法 參考:http://www.tuicool.com/articles/biy6na 解决方法: step1: 到 sqlite官网 (http ...
- 【点击模型学习笔记】Predicting Clicks_Estimating the Click-Through Rate for New Ads_MS_www2007
概要: 微软研究院的人写的文章,提出用逻辑回归来解决ctr预估问题,是以后ctr的经典解决方式,经典文章. 详细内容: 名词: CPC -- cost per click CTR -- click t ...
- 力挺8天入门wpf【转载】
8天入门wpf—— 第八天 最后的补充 摘要: 从这一篇往前看,其实wpf中还有很多东西没有讲到,不过我的原则还是将比较常用的知识点过一遍,如果大家熟悉了这些知识,基本功也就打的差不多了,后续可以等待 ...
- <源代码>FTPclient追加方式上传自己定义信息
实现功能:向FTPserver以追加方式上传自己定义信息(例程中为:2014-10-08 13:47:15 test.) 源代码下载(免积分):http://download.csdn.net/det ...
- AC自动机跟随Kuangbing学习笔记
http://www.cnblogs.com/kuangbin/p/3164106.html kuangbin的博客 第一段代码基本是COPY kuangbin的.. 1.HDU 2222 Keywo ...
- SQL Server 强行Insert包含自增列值的记录
SET IDENTITY_INSERT 表 ON INSERT INTO 表 ([ID] ,[SequenceNumber] ,[EnumCode] ,[Description]) VALUES ( ...