![](/img/trans.png)
[英]How to copy value of one data column into another data column in the same data table C#?
[英]How to copy data from one column to another at the same datatable in 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的值僅復制到該行?
這是完整的代碼:
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];
,順便說一句,您的示例缺少括號。
我認為您應該根據問題所在的條件來檢查代碼,也可以自己完成。 只需注意您在問題中編寫的條件和在代碼中簽入的條件運算符即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.