C#Excel有条件地剪切/粘贴单元格

如何检查我的两列(列I和列H)以查看是否在列I中,如果有任何单元格是非空的,列H中的单元格是空的,则将列I中的非空单元格剪切并粘贴到空细胞在列H.

举一个更清晰的例子:

在这里输入图像说明

我的想法到目前为止是如此:

xl.Range ColH = sourceSheet.UsedRange; xl.Range ColI = sourceSheet.UsedRange; string occupiedCellsH; string emptyCellsI; occupiedCellsH = ColH.ToString(); emptyCellsI = ColI.ToString(); if (string.IsNullOrEmpty(emptyCellsI) && occupiedCellsH != null) { ColH.Cells.Copy(ColI);; } 

这将做的伎俩:

  const int hCol = 8; const int iCol = 9; //start at 1 as there are column headings for (int i = 1; i < sourceSheet.UsedRange.Rows.Count; i++) { if ((sourceSheet.cells[i, hCol].value??"").ToString()!="" && (sourceSheet.cells[i, iCol].value??"").ToString()=="") { sourceSheet.cells[i, iCol].value = sourceSheet.cells[i, hCol].value; sourceSheet.cells[i, hCol].value = ""; } } 

按照你的评论做相反的事(假设你仍然需要这个):

  const int hCol = 8; const int iCol = 9; //start at 1 as there are column headings for (int i = 1; i < sourceSheet.UsedRange.Rows.Count; i++) { if ((sourceSheet.cells[i, iCol].value??"").ToString()!="" && (sourceSheet.cells[i, hCol].value??"").ToString()=="") { sourceSheet.cells[i, hCol].value = sourceSheet.cells[i, iCol].value; sourceSheet.cells[i, iCol].value = ""; } }