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

时间:2016-12-09 10:29:26

标签: c# excel paste

如何查看我的两列(第一列和第二列)以查看是否在第一列中,是否有任何单元格为空,而在列H中单元格为空,然后剪切并粘贴第一列中的非空单元格到H列中的空单元格。

有一个更清晰的例子:

enter image description here

到目前为止我的想法是这样的:

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);;
        }

1 个答案:

答案 0 :(得分:2)

这样可以解决问题:

        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 = "";
            }
        }