如何将Gridview导出到Excel,在本地工作,但在通过IIS部署时不工作

时间:2016-07-13 06:11:06

标签: mysql asp.net excel iis gridview

我的Web应用程序连接到MySql数据库,用户通过选择日期范围来筛选Gridview中的数据,我现在的问题是当用户单击Export_button时,Exportfile(Excel)显示但不是在用户计算机中而是在服务器中?我希望它用他们的电脑显示它,你能帮助我吗?谢谢你的回复。

Export_Button中的代码

 protected void Export_Click(object sender, EventArgs e)
    {
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Visible = true;
            Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
            Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
            int StartCol = 1;
            int StartRow = 1;
            int j = 0, i = 0;

            //Write Headers

            for (j = 0; j < GridView1.Columns.Count; j++)
                {
                Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
                myRange.Value2 = GridView1.Columns[j].HeaderText;
                }

            StartRow++;

            //Write datagridview content
            for (i = 0; i < GridView1.Rows.Count; i++)
            {
                for (j = 0; j < GridView1.Columns.Count; j++)
                {
                    try
                    {
                        Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];
                        myRange.Value2 = GridView1.Rows[i].Cells[j].Text == null ? "" : GridView1.Rows[i].Cells[j].Text;
                    }
                    catch
                    {
                        ;
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

在彻底搜索网后,我终于解决了我的问题,希望它能在不久的将来帮助你。

我使用Aspose方法,它是伟大而完美的解决方案!下面是我的新代码,我的Export_Button希望它有所帮助!

     //Instantiate a new workbook
            Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
            //Get the first worksheet in the workbook
            Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
            //Import data from GridView control to fill the worksheet
            worksheet.Cells.ImportGridView(GridView1, 0, 0, new Aspose.Cells.ImportTableOptions() { IsFieldNameShown = true });
            worksheet.AutoFitColumns();
            //Send result to client in XLS format
            workbook.Save(this.Response, "export.xls", ContentDisposition.Attachment, new Aspose.Cells.XlsSaveOptions());