小狼人Lv92
c# Recordset转datatable 方法
/// <summary> /// Recordset转datatable /// </summary> /// <param name="recordset"></param> /// <returns></returns> private DataTable ConvertRecordsetToDataTable(ADODB.Recordset recordset) { DataTable dataTable = new DataTable(); dataTable.Namespace = null; // 添加列 for (int i = 0; i < recordset.Fields.Count; i++) { dataTable.Columns.Add(GetUniqueColumnName(dataTable,recordset.Fields[i].Name) ,typeof(string)); } // 添加数据 recordset.MoveFirst(); while (!recordset.EOF) { var dataRow = dataTable.NewRow(); for (int i = 0; i < recordset.Fields.Count; i++) { var field = recordset.Fields[i]; dataRow[i] = field.Value; } dataTable.Rows.Add(dataRow); recordset.MoveNext(); } return dataTable; } /// <summary> /// 设置datatable唯一列名 /// </summary> /// <param name="dataTable"></param> /// <param name="baseColumnName"></param> /// <returns></returns> private string GetUniqueColumnName(DataTable dataTable,string baseColumnName) { string columnName = baseColumnName; // 如果列名已存在,追加数字后缀,直到找到一个唯一的列名 int suffix = 1; while (dataTable.Columns.Contains(columnName)) { columnName = baseColumnName+"_"+suffix; suffix++; } return columnName; }
0 已被阅读了733次 楼主 2023-12-01 16:16:09