C#Winform中的DataGridView控件中导出至Excel如何对列值进行合计?求示例

解决方案 »

  1.   

     public void ExportDataGridToExcel(DataGridView grid, string ReportTitle)
            {
                DataTable myTable = (DataTable)grid.DataSource;            try
                {
                    Excel.Application xlApp = new Excel.ApplicationClass();                int rowIndex;
                    int colIndex;                rowIndex = 2;
                    colIndex = 0;                Excel.Workbook xlBook = xlApp.Workbooks.Add(true);                if (grid.Rows.Count > 0)
                    {
                        Excel.Range range = xlApp.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, 2]);
                        range.MergeCells = true;
                        xlApp.ActiveCell.FormulaR1C1 = ReportTitle;
                        xlApp.ActiveCell.Font.Size = 18;
                        xlApp.ActiveCell.Font.Bold = true;                    foreach (DataGridViewColumn column in grid.Columns)
                        {
                            colIndex++;
                            xlApp.Cells[2, colIndex] = column.HeaderText;
                        }                    //得到的表所有行,赋值给单元格
                        for (int row = 0; row < myTable.Rows.Count; row++)
                        {
                            rowIndex++;
                            colIndex = 0;
                            for (int col = 0; col < grid.Columns.Count; col++)
                            {
                                colIndex = colIndex + 1;
                                xlApp.Cells[rowIndex, colIndex] = grid[col, row].Value;
                            }
                        }                    xlApp.get_Range(xlApp.Cells[2, 1], xlApp.Cells[2, colIndex]).Font.Bold = true;
                        xlApp.get_Range(xlApp.Cells[2, 1], xlApp.Cells[rowIndex, colIndex]).Borders.LineStyle = 1;
                    }
                    xlApp.Cells.EntireColumn.AutoFit();
                    xlApp.Cells.VerticalAlignment = Excel.Constants.xlCenter;
                    xlApp.Cells.HorizontalAlignment = Excel.Constants.xlCenter;                xlApp.Visible = true;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
      

  2.   

    在DataGridView控件里追加一行记录?偶新手不懂