[英]How do i add columns to datatable from rows from another datatable
我有一個名為dt
的數據表,其中填充了來自excel的值。
在第6行(行)上,我有我的標題信息
我現在有密碼
string connString = @"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\thoje\Desktop\stack\forslag.xlsx;" +
@"Extended Properties=""Excel 12.0;HDR=No;""";
DataTable dt = new DataTable();
string sql = @"SELECT * from [Ark1$]";
using (OleDbConnection conn = new OleDbConnection(connString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
}
}
}
DataTable dt2 = dt.Clone();
//foreach (DataRow dr in dt.Rows)
//{
for (int i = 5; i <= dt.Rows.Count-1; i++)
{
if (i == 6)
{
DataRow dr = dt2.NewRow();
dr.ItemArray = dt.Rows[i].ItemArray;
dt2.Rows.Add(dr);
}
else if(i >=8)
{
DataRow dr = dt2.NewRow();
dr.ItemArray = dt.Rows[i].ItemArray;
dt2.Rows.Add(dr);
}
}
我需要的是:
- 我希望第6行上的所有數據成為新DataTable中的標題
- 第7行之后的所有數據我都需要使用新的標頭附加到此新的Datatable中。
我的代碼顯示了什么:
我的代碼現在顯示了如何在克隆的DataTable上執行此操作,因此我的頭名錯誤。
如果只需要其中一行,則不需要遍歷所有行。
DataTable dtSource = new DataTable();
DataTable dtTarget = new DataTable();
// Get row at index == 6 (7th line as this is a 0-based-index)
var headerRow = dtSource.Rows[6];
// Iterate through all values
foreach(var value in headerRow.ItemArray)
{
// For each value create a column
// and add it to your new dataTable
DataColumn dc = new DataColumn(value.ToString());
dc.Caption = value.ToString();
dtTarget.Columns.Add(dc);
}
使用linq方法可能會很好:偽方式:
//linq query to select row
var query = from myRow in
myDataTable.AsEnumerable() where myRow.Field<int>("RowNo") == 6
select myRow;
// Create a table from the query DataTable newTable =
query.CopyToDataTable<DataRow>();
您的問題很難看清,並且一直在談論我期望列等的行,但是我將做出以下假設:
碼:
for(int i = 5; i >= 0; i--){
if(i == 5)
{
for(int j = 0; j < dt.Columns.Count; j++)
dt.Columns[j].ColumnName = dt.Rows[i][j].ToString();
}
dt.Rows.RemoveAt(i);
}
您無需克隆數據表。 當心那些導致較差列名的字符串(包含諸如“ [”)之類的字符,使您的生活更加痛苦。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.