【问题标题】:Call and export two Gridviews into two separate worksheets调用两个 Gridview 并将其导出到两个单独的工作表中
【发布时间】:2015-10-13 02:00:53
【问题描述】:

我想将gridview1gridview2 导出到两个单独的工作表中,这些工作表可以在我的代码中命名为grid view 1grid view 2 在一个Excel 文件中。我在导出到 Excel 时遇到问题,不知道如何在按钮中调用我的导出并将参数传入以导出两个 Gridview:

public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
        {
            // creating new Excelsheet in workbook
            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

            // see the excel sheet behind the program
            app.Visible = true;

            // get the reference of first sheet. By default its name is Sheet1.
            // store its reference to worksheet
            worksheet = workbook.Sheets["Sheet" + sheetid];
            worksheet = workbook.ActiveSheet;

            // 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();
                }
            }


            // save the application
            workbook.SaveAs(@"C:\Users\testacc\Desktop\Test\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            // Exit from the application
            app.Quit();
        }

下面的代码应该放在哪里?

// creating Excel Application
 Microsoft.Office.Interop.Excel._Application app  = new Microsoft.Office.Interop.Excel.Application();

// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook =  app.Workbooks.Add(Type.Missing);

【问题讨论】:

    标签: c# asp.net excel gridview


    【解决方案1】:

    您必须在

    中创建这些对象

    公共无效调用函数(){

    Microsoft.Office.Interop.Excel._Application app  
          = new Microsoft.Office.Interop.Excel.Application();
    
    // creating new WorkBook within Excel application
    Microsoft.Office.Interop.Excel._Workbook workbook 
         =   app.Workbooks.Add(Type.Missing);
    
    
    
    ExportToExcel(app, workbook, gv1, 'sheet1', 1)
    
    ExportToExcel(app, workbook, gv2, 'sheet2', 2)   
    }
    

    【讨论】:

    猜你喜欢
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多