How do I format my export to excel workbook in microsoft.office.interop.excel?

前端 未结 4 687
醉梦人生
醉梦人生 2021-01-28 10:39

I have this export function that allows me to export 2 grid views into 2 separated worksheets in one excel.

But my problems are:

  1. How can I have a usual

4条回答
  •  余生分开走
    2021-01-28 11:19

    as specified by Laxmikant modify the code of your method "ExportToExcel" as follows.

    public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
    {
    
    // see the excel sheet behind the program
    app.Visible = true;
    
    worksheet = (Excel.Worksheet)workbook.Worksheets.Add();
    
    // changing the name of active sheet
    worksheet.Name = SheetName;
    
    // storing header part in Excel
    for (int i = 1; i < gridview.Columns.Count + 1; i++)
    {
        worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
    }
    
    // storing Each row and column value to excel sheet
    for (int i = 0; i < gridview.Rows.Count - 1; i++)
    {
        for (int j = 0; j < gridview.Columns.Count; j++)
        {
            worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
        }
    }
    

    I removed these two lines of code and now there is no need of the parameter "Sheetid"

    Excel.Worksheet worksheet =(Excel.Worksheet)workbook.Worksheets["Sheet" + sheetid];
    worksheet = workbook.ActiveSheet;
    

    Hope this will solve your issue

提交回复
热议问题