简体   繁体   English

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

[英]C# Excel Cut/Paste cells conditionally

How do I check my two columns (column I and column H) to see if in column I, if any cells are non-empty, and column H the cells are empty then cut and paste the non empty cell from column I to the empty cell in column H. 如何检查我的两列(I列和H列)以查看I列中是否有非空单元格,而H列中的单元格为空,然后将非空单元格从I列剪切并粘贴到空H列中的单元格。

For a more clear example : 举一个更清晰的例子:

在此处输入图片说明

My idea so far was as so: 到目前为止,我的想法是这样的:

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

This will do the trick: 这将达到目的:

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

To do the reverse as per your comment (assuming you still need this): 按照您的评论进行相反操作(假设您仍然需要这样做):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM