C# Excel Cut/Paste 有条件的单元格

C# Excel Cut/Paste cells conditionally

如何检查我的两列(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 = "";
            }
        }