C#到Excel,查找使用的最后一行

本文关键字:最后 一行 Excel 查找 | 更新日期: 2023-09-27 18:22:14

下面是我的C#代码,用于将动态创建的文本框发送到Excel。我需要找到用于这些文本框的最后一行,这样我就可以在第一组下面的6行开始下一个for循环。

int StartBundleRow = 11;
for (int BndlRow = 0; BndlRow < bundleRows; BndlRow++) //add bundle rows to spreadsheet
{
    worksheet.Rows[StartBundleRow].Insert();
    worksheet.Cells[StartBundleRow, "D"].value = srcBundlePanel.Controls["txtQtyBundle" + BndlRow].Text;
    worksheet.Cells[StartBundleRow, "E"].value = srcBundlePanel.Controls["txtProductNameBundle" + BndlRow].Text;
    worksheet.Cells[StartBundleRow, "F"].value = srcBundlePanel.Controls["txtListPriceBundle" + BndlRow].Text;
    worksheet.Cells[StartBundleRow, "G"].value = srcBundlePanel.Controls["txtMaxDiscountBundle" + BndlRow].Text;
    worksheet.Cells[StartBundleRow++, "H"].value = srcBundlePanel.Controls["txtProposedPriceBundle" + BndlRow].Text;
}

C#到Excel,查找使用的最后一行

每次需要运行序列时,您也可以使用类似的东西:

int numRows = sheet.UsedRange.Rows.Count;

图纸类型为Microsoft.Office.Interop.Excel.Worksheet

您可以这样做:

const int ROW_CUSHION = 6;
int StartBundleRow = 11;
int nextStartingRow = StartBundleRow;
for (int BndlRow = 0; BndlRow < bundleRows; BndlRow++) //add bundle rows to spreadsheet
{
    worksheet.Rows[StartBundleRow].Insert();
    worksheet.Cells[StartBundleRow, "D"].value = srcBundlePanel.Controls["txtQtyBundle" + BndlRow].Text;
    worksheet.Cells[StartBundleRow, "E"].value = srcBundlePanel.Controls["txtProductNameBundle" + BndlRow].Text;
    worksheet.Cells[StartBundleRow, "F"].value = srcBundlePanel.Controls["txtListPriceBundle" + BndlRow].Text;
    worksheet.Cells[StartBundleRow, "G"].value = srcBundlePanel.Controls["txtMaxDiscountBundle" + BndlRow].Text;
    worksheet.Cells[StartBundleRow++, "H"].value = srcBundlePanel.Controls["txtProposedPriceBundle" + BndlRow].Text;
}
nextStartingRow = nextStartingRow + ROW_CUSHION;

例如,这里摘录了我的一些类似代码:

const int TIMES_BEFORE_ITS_CHARMING = 3;
private int _lastRowAdded;
. . .
_lastRowAdded = _curDescriptionTopRow + TIMES_BEFORE_ITS_CHARMING;
. . .
var descriptionColRange = _xlSheet.Range[_xlSheet.Cells[DATA_STARTING_ROW, ITEMDESC_COL], _xlSheet.Cells[_lastRowAdded, ITEMDESC_COL]];

所以我根据另一个值+一个"缓冲"值(上面的3)给它赋值;它可以根据需要在整个代码中进行更新。然后我用这个值来描述要操作的单元格范围。