我有一个数据表填充了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;
}
答案 0 :(得分:1)
添加行使用dt.Rows.Add(row);
,关于&#34;将列B复制到A&#34;你的意思是复制值,顺便指一下row[0] = row[2];
,你的例子缺少一个括号。
我认为你应该根据问题中的条件审核你的代码,你也可以自己做。只需注意你写的条件和你在代码中检查的条件运算符。