内容列表
属性
- 获取行列数
方法
- 添加列
- 添加行
- 删除行列
- 获取列名
- 获取列类型
- 更改列名
- 获取单元格数值
- 写入数值到单元格
其它
- 转置
- 将一张表的某列添加到另一张表
- 将一张表的某行添加到另一张表
属性
获取行列数
int numOfRows = dt.Rows.Count; int numOfCols = dt.Columns.Count;
方法
添加列
dt.Columns.Add("Name", typeof(string)).SetOrdinal(0);//to the first column DataColumn dc1 = new DataColumn("Tol", typeof(string)); dt.Columns.Add(dc1);
添加行
//method1 DataRow dr1 = dt.NewRow(); dt.Rows.Add(dr1); //method2 dt.Rows.Add();
删除行列
dt.Columns.RemoveAt(index);//index is location of coldt.Rows.RemoveAt(index);
获取列名
dt.Columns[i].ColumnName.ToString();
获取列类型
Type dataType= dataDt.Columns["Name"].DataType
更改列名
dt.Columns[0].ColumnName = "AAA";
获取单元格数值
var val = dt.Rows[i][j].toString();
写入数值到单元格
dt.Rows[i][j]=val;//The type of val should be the same as the column, which the cell belongs to
完整代码
private void tableoperations() { System.Data.DataTable dt = new System.Data.DataTable(); int index = 0; int i = 0, j = 0; //add new column dt.Columns.Add("Name", typeof(string)).SetOrdinal(0);//to the first column DataColumn dc1 = new DataColumn("Tol", typeof(string)); dt.Columns.Add(dc1); //add new row //method1 DataRow dr1 = dt.NewRow(); dt.Rows.Add(dr1); //method2 dt.Rows.Add(); //delet columns dt.Columns.RemoveAt(index); //delet rows dt.Rows.RemoveAt(index); //get the column name dt.Columns[i].ColumnName.ToString(); //change columns name: dt.Columns[0].ColumnName = "AAA"; //read/write the cell value dt.Rows[i][j] = 1; //get column type Type dataType = dt.Columns["Name"].DataType; }
其它
转置
private System.Data.DataTable transpositioin(System.Data.DataTable tb_org, int col_start = 0)//the original one has names of rows and columns { System.Data.DataTable tb_trans = new System.Data.DataTable(); tb_trans.Columns.Add("item", typeof(string)); for (int i = 0; i < tb_org.Rows.Count; i++) { tb_trans.Columns.Add(tb_org.Rows[i][col_start].ToString(), typeof(string));//can change the type } for (int i = 0; i < tb_org.Columns.Count; i++) {//here i only need to start from the (start+1)th column tb_trans.Rows.Add(); tb_trans.Rows[i][0] = tb_org.Columns[i].ColumnName.ToString();//add row name for (int j = 0; j < tb_org.Rows.Count; j++) { tb_trans.Rows[i][j + 1] = double.Parse(tb_org.Rows[j][i].ToString());//add value, the first column is the orinigal column name } } return tb_trans; }
将一张表的某列添加到另一张表(行添加的同理)
private System.Data.DataTable getcolumn(System.Data.DataTable tb_WithTarCol) { System.Data.DataTable tb = new System.Data.DataTable(); tb.Columns.Add(tb_WithTarCol.Columns[0].ColumnName.ToString(), typeof(string));//here, get the first column foreach (DataRow dr in tb_WithTarCol.Rows) { DataRow tmp = tb.NewRow(); tmp[0] = dr[0];//get the first cell, which belongs to the first column tb.Rows.Add(tmp); } return tb; }
原文地址:https://www.cnblogs.com/RicardoIsLearning/p/12116037.html
时间: 2024-10-05 04:56:12