如何将数据从一列复制到另一个在c#中相同的数据表

我有一个从excel文件中填充信息的数据表。 我有四个以上的专栏,但要举一个例子,我只写了四个。 我必须编写一个程序,如果列C中的单元格的值是0,那么我必须将列B复制到列A.如果列C中的单元格的值是> 0,那么我必须复制列B到A,并应该添加另一行,我必须将列C的值复制到A. 在这里输入图像说明

我到现在为止是

for (int r = 2; r <= ws.UsedRange.Rows.Count; r++) { if (ws.UsedRange.Cells[r, 3].Text == "0") { DataRow row = dt.NewRow(); for (int c = 1; c < ws.UsedRange.Columns.Count; c++) { string cell = ws.Cells[r, c].Text; row[c - 1] = cell; } } 

所以我的问题是:

我怎样才能在同一个数据表复制列到另一个? 将B复制到A.如何添加另一行并将C的值仅复制到A行?

以下是完整的代码:

  public DataTable ReadExcel2(string file) { ExcelI.Application app = new ExcelI.Application(); //create an excel instance ExcelI.Workbook wb = app.Workbooks.Open(file, ReadOnly: true); //open a file ExcelI.Worksheet ws = wb.Worksheets[1]; //choose a sheet. The firt one var rng = ws.UsedRange; //takes the index of the columns that are going to be filtered int service = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Service"); int status = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Status"); int code = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Code"); DataTable dt = new DataTable(); dt.Columns.Add("A", typeof(string)); for (int c = 1; c < ws.UsedRange.Columns.Count; c++) { string colName = ws.Cells[1, c].Text; int i = 2; while (dt.Columns.Contains(colName)) { colName = ws.Cells[1, c].Text + "{" + i.ToString() + "}"; i++; } dt.Columns.Add(colName); } //do a loop to delete the rows that we dont need for (int r = 2; r <= ws.UsedRange.Rows.Count; r++) { if (ws.UsedRange.Cells[r, 3].Text == "0") { DataRow row = dt.NewRow(); for (int c = 1; c < ws.UsedRange.Columns.Count; c++) { string cell = ws.Cells[r, c].Text; row[c - 1] = cell; } dt.Rows.Add(row); row["A"] = row["C"]; } } //Close the file wb.Close(); //release the excel objects from use Marshal.ReleaseComObject(wb); Marshal.ReleaseComObject(ws); //take the id of excel process int pid = app.PID(); app.Quit(); StartProc("taskkill", $"/f /pid {pid}"); return dt; } 

添加行使用dt.Rows.Add(row); ,关于“将B列复制到A”意味着复制值,只需分配row[0] = row[2]; 顺便说一下,你的例子中缺less一个括号。

我认为你应该根据你的问题的条件来检查你的代码,你也可以自己做。 只要注意你所写的条件和你在代码中签入的条件操作符。