Click here to Skip to main content
15,915,093 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I want to add the Totals of my datagridview Column at the bottom of where I insert my DataGridView into a excel worksheet. So if my Datagrid contains a column that's has numbers in the rows of the column. I want to add the SUM of all those numbers to the end of the column that has the values. To get the totals is no problem. It's in a textbox at the moment.

This is how I add my DataGrid to the Excel Sheet. I can generate the totals of the column and add it into a textbox. No problem. Just need to get that total in the textbox at he end of the Datagrid section where it is generated in the Excel Sheet. Problem is the datagrid has various sizes (meaning rows) so that cell with the total will not always be in the same place.....

C#
int i = 0;
int j = 0;

for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
    for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
    {
        DataGridViewCell cell = dataGridView1[j, i];
        xlWorkSheet.Cells[i + 23, j + 1] = cell.Value;
    }

}


Thanks Any help will do.....
Posted

Hi,Dirk
you can use the RowCount property of your DataGridView to access to the last row of it :
C#
dataGridView1.Rows[dataGridView1.RowCount].Cells["CellName"].Value = txtTotal.Text;


and then add it to Excel Sheet with other values of datagrid.
 
Share this answer
 
So I came up with this solution. Add int to select the column (k) in this case, then use i int + 1 to place it underneath the datagrid. Working 100% Yeh!

Thank for you suggestion thoung phoenix1167 :-)

C#
int i = 0;
           int j = 0;
           int k = 2;
           int l = 1;

           for (i = 0; i <= dataGridView1.RowCount - 1; i++)
           {
               for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
               {
                   DataGridViewCell cell = dataGridView1[j, i];
                   xlWorkSheet.Cells[i + 18, j + 1] = cell.Value;
                   xlWorkSheet.Cells[i + 18 + 1, k + 1] = label13.Text;
                   xlWorkSheet.Cells[i + 18 + 1, l + 1] = "Total:";

               }

           }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900