You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#操作Excel:添加单行数据后终止while循环的问题

解决C#操作Excel添加数据的循环问题

嘿,我来帮你搞定这个头疼的循环问题!首先得戳破核心问题:Excel的Cells对象永远不会返回null——哪怕单元格是空的,它也会返回一个有效的Cell实例,所以你原来的while(oSheet.Cells[inc,1] != null)条件永远为true,直接导致无限循环。而带break的代码里,你刚给单元格赋值完,它肯定不是null,所以第一次循环就直接跳出了,根本没机会定位到正确的空行。

正确的思路:直接定位最后一行,无需循环

其实你完全不需要用循环逐行判断,Excel本身提供了高效的方法来定位第一列最后一个有数据的行,然后直接在它的下一行插入数据即可,一步到位:

private void btnCreateClaim_Click(object sender, EventArgs e) {
    Excel.Application oXL;
    Excel._Workbook oWB;
    Excel._Worksheet oSheet;
    oXL = new Excel.Application();
    oXL.Visible = true;
    oWB = oXL.Application.Workbooks.Open(@"C:\CSAIO4D\testsheet1.xlsx");
    oSheet = oWB.ActiveSheet;

    // 定位第一列最后一个有数据的行
    int lastRow = oSheet.Cells[oSheet.Rows.Count, 1].End(Excel.XlDirection.xlUp).Row;
    // 要插入数据的行是最后一行的下一行
    int insertRow = lastRow + 1;

    // 给目标行赋值
    oSheet.Cells[insertRow, 1] = txtClientName.Text.ToString();
    oSheet.Cells[insertRow, 2] = txtState.Text.ToString();
    oSheet.Cells[insertRow, 3] = txtAlphaPrefix.Text.ToString();
    oSheet.Cells[insertRow, 4] = txtInsurance.Text.ToString();
    oSheet.Cells[insertRow, 5] = txtStartDate.Text.ToString();
    oSheet.Cells[insertRow, 6] = txtEndDate.Text.ToString();
    oSheet.Cells[insertRow, 7] = txtUnits.Text.ToString();
    oSheet.Cells[insertRow, 8] = txtLOC.Text.ToString();
    oSheet.Cells[insertRow, 9] = txtRate.Text.ToString();
    oSheet.Cells[insertRow, 10] = txtAmount.Text.ToString();
    oSheet.Cells[insertRow, 11] = txtAuth.Text.ToString();
    oSheet.Cells[insertRow, 12] = txtBilledDate.Text.ToString();
    oSheet.Cells[insertRow, 13] = txtPrimaryDiagnosis.Text.ToString();
    oSheet.Cells[insertRow, 14] = txtBillType.Text.ToString();
    oSheet.Cells[insertRow, 15] = txtRevenueCode.Text.ToString();
    oSheet.Cells[insertRow, 16] = txtHCPCS.Text.ToString();
    oSheet.Cells[insertRow, 17] = txtCPT_Code.Text.ToString();

    oWB.Save();

    // 好习惯:释放Excel对象,避免内存泄漏
    oWB.Close();
    oXL.Quit();
    System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
}

为什么这个方法靠谱?

  • oSheet.Cells[oSheet.Rows.Count, 1]定位到第一列的最后一个单元格(Excel最大行数)
  • .End(Excel.XlDirection.xlUp)相当于手动按Ctrl+Up,直接跳转到第一列最后一个有数据的单元格
  • 取这个单元格的Row属性就是最后一行的行号,加1就是我们要插入数据的空行

如果非要用循环(不推荐)

如果你坚持想用循环的方式,那应该判断单元格的Value是否为空,而不是判断Cell对象是否为null,修改后的循环逻辑如下:

int inc = 1;
// 判断单元格Value是否为空或空字符串
while (!string.IsNullOrEmpty(oSheet.Cells[inc, 1].Value?.ToString()))
{
    inc++;
}
// 此时inc就是第一个空行的行号,直接赋值
oSheet.Cells[inc, 1] = txtClientName.Text.ToString();
// ... 其他单元格赋值

这个方式虽然能工作,但效率远不如直接定位最后一行,尤其是当Excel数据量很大的时候。

内容的提问来源于stack exchange,提问作者Matt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:30:18