将GridView导出为现有Excel作为新工作表

时间:2014-12-25 04:22:15

标签: asp.net excel gridview

我在我的网络应用程序中有GridView,同时点击导出按钮,将gridview中的值导出到现有excel文件中的新工作表中,相应地为Day1,Day2,...

谢谢!

2 个答案:

答案 0 :(得分:0)

请仔细阅读本文

http://www.aspsnippets.com/Articles/Export-GridView-to-Excel-in-ASPNet-with-Formatting-using-C-and-VBNet.aspx

Key是GridView1.RenderControl(hw),它将gridview的内容呈现为字符串,并通过设置Response.ContentType和Header(content-disposition)将允许您生成gridview的数据为xls。

答案 1 :(得分:0)

您可以使用EPPlus Library进行此操作,以下是有关如何创建工作表的快速摘录:

 string filePath = "~/App_Data/emptyExcelFile.xlsx";
 FileInfo fi = new FileInfo(Server.MapPath(filePath));
 using (ExcelPackage xlPackage = new ExcelPackage(fi))
 {
     for (int i = 1; i <= 3; i++)
     {
        ExcelWorksheet worksheet;
        worksheet = xlPackage.Workbook.Worksheets.Add("Day"+i, sheetName);
     }

     Response.Clear();
     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
     Response.AddHeader("content-disposition", "attachment;  filename=" + "myExcelFile.xlsx");
     Response.BinaryWrite(xlPackage.GetAsByteArray());
     Response.Flush();
     Response.End();
  }

希望这有帮助。