简体   繁体   English

C# 循环到 Excel 中的特定行

[英]C# loop to specific rows in Excel

Can anyone help me I want my C# code to start loop and print at row number 5 in my Excel file.谁能帮助我我希望我的 C# 代码开始循环并在我的 Excel 文件中的第 5 行打印。

Here is my current code:这是我当前的代码:

            DataColumnCollection dataColumnCollection = dataTable.Columns;

            for (int i = 1; i <= dataTable.Rows.Count + 1; i++)
            {
                for (int j = 1; j <= dataTable.Columns.Count; j++)
                {
                    if (i == 1)
                        excelApplication.Cells[i, j] = dataColumnCollection[j - 1].ToString();
                    else
                        excelApplication.Cells[i, j] = dataTable.Rows[i - 2][j - 1].ToString();
                }

Here is my sample data: sample data这是我的示例数据:示例数据

And here is what I want the file to look like: sample result这是我希望文件的样子:示例结果

first of all arrays and lists the like start at 0 in most cases.首先是 arrays 并在大多数情况下从0开始列出类似内容。

In your case if you want to start at row 5, simply increment the start with 5.在您的情况下,如果您想从第 5 行开始,只需从 5 开始递增。

            const int start = 5;
            int end = datadataTable.Rows.Count;
            for (int i = 0 + start; i < end; i++) // loop from 5..end
            {

                for (int j = 1; j <= dataTable.Columns.Count; j++)
                {
                    if (i == 1)
                        excelApplication.Cells[i, j] = dataColumnCollection[j - 1].ToString();
                    else
                        excelApplication.Cells[i, j] = dataTable.Rows[i - 2][j - 1].ToString();
                }

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

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