当前位置:编程学习 > 网站相关 >>

动态创建DataTable

 


代码实例如下:

DataTable table = null;

//要素指针
IFeatureCursor pFeatureCursor = null;
IFeature pFeature = null;
for (int i = 0; i < featureClassList.Count; i++)
{
//获得Excel文件的文件名不包括后缀
string fileName = getFileNameBasedOnFeatureClassAliasName(featureClassList[i].AliasName);
string saveFullName = System.IO.Path.Combine(mTempCreateFilesDir, fileName+".xls");
mExcelFilesList.Add(fileName);//将文件名添入Excel文件名集合中
pFeatureCursor = featureClassList[i].Search(null, true);//要素指针赋值:条件需要限制
pFeature = pFeatureCursor.NextFeature();

table = new DataTable();
//定义DataTable的列,指定列名
for (int k = 0; k < featureClassList[i].Fields.FieldCount; k++)
{
string columnName = featureClassList[i].Fields.Field[k].Name;
table.Columns.Add(columnName);
}
//创建行
while (pFeature != null)
{
DataRow dr = table.NewRow();//创建表的新行
for (int j = 0; j < pFeature.Fields.FieldCount; j++)
{
IField field = pFeature.Fields.Field[j];
int sourceFieldIndex = pFeature.Fields.FindField(field.Name);
if (sourceFieldIndex < 0)
{
continue;
}

object obj = pFeature.get_Value(sourceFieldIndex);
dr[field.Name] = obj;
}
table.Rows.Add(dr);
pFeature = pFeatureCursor.NextFeature();
}
ExcelHelper.DataSetToExcel(saveFullName, table);//将DataTable的数据集导入到Excel文件中


}

 


总结:

1、先创建Columns,用到table.Columns.Add(columnName);方法

2、再动态的为table创建新行,用DataRow dr=table.NewRow()

3、为新行的每一列赋值,dr[field.Name] = obj;

4、将新行添加到table中,table.Rows.Add(dr);

 

补充:综合编程 , 其他综合 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,