简体   繁体   中英

C# filling excel from datagridview until getting to a certain column

Basically what I need to do is, I have a lot of data that takes up 1 cell per row loaded into a datagridview, and I want to pivot it, and export it to an excel file. So what I have is a vertical list, and I would like to make it horizontal, but I only need the cells to be filled until getting to column 'L', and when the data gets to it, then it starts again at the next row, and repeating this until dgv has no more data to fill in to the excel. So far what I have is:

private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp = new Excel.Application();
        Excel.Worksheet xlsht = new Excel.Worksheet();
        Microsoft.Office.Interop.Excel.Workbook xlwb;
        xlApp.Visible = true;
        string path = @"myfilepath";
        xlwb = xlApp.Workbooks.Open(path);
        xlsht = xlwb.Worksheets["Tabelle1"];
        
        for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
        {

            for (int j = 1; j < 12; j++)
            {
                xlsht.Cells[i + 1, j] = dataGridView1.Rows[i].Cells[0].Value.ToString();
            }       

        }

The problem with this is the following: it fills the cells with the same value, until getting to the column 'L' (11th column, that's why I have 12 in the nested for loop), and then it starts again in the next row, but again, repeating the next value(to clarify, the value in the first row is 1, so it repeats 1 until getting to the 11th column.Then it starts again with the next value, for example 2, and does the same thing). How could I fix this? Thanks in advance!

You need to separate the Excel row and column indexes from the loop through the grids rows. All you need is one loop though all the rows to add the first column of that row to the worksheet. To keep it simple, pull the Excel indexs and manually update them.

In the loop through the rows, increment the worksheets column index by 1 until it reaches 12, Then increment the excel row index by 1 and reset the excel column back to 1.

Something like….

int xlRow = 1;
int xlCol = 1;
for (int i = 0; i < dataGridView1.Rows.Count; i++) {
  if (!dataGridView1.Rows[i].IsNewRow) {
    xlsht.Cells[xlRow, xlCol] = dataGridView1.Rows[i].Cells[0].Value.ToString();
    if (xlCol == 12) {
      xlRow++;
      xlCol = 1;
    }
    else {
      xlCol++;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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