如何在不使用Microsoft引用的情况下为Excel报表创建页面

时间:2014-04-16 14:07:25

标签: c# excel gridview

我有这种创建Excel spreedsheet的方法,下面列出了我的数据。

List<ReportData> rd = ReportData.getReportData(startTime, endTime, lNumber, sNumber);
    DataTable dt = buildDataTable(rd);


    //we actually ahve to have a gridview to put into excel
    GridView gv = new GridView();
    gv.DataSource = dt;
    gv.DataBind();

    //flush everything from response to be sure we get a clean start
    Response.ClearContent();


    //now we create excel file
    Response.AddHeader("content-disposition", "attachment;filename=UserRpt.xls");
    Response.ContentType = "application/vnd.ms-excel";
    Response.Charset = "";

    StringWriter sw = new StringWriter();
    HtmlTextWriter tw = new HtmlTextWriter(sw);
    gv.RenderControl(tw);

    //send xls as response

    Response.Write(sw.ToString());
    Response.End();

我的问题是如何让它创建更多页面并将数据写入它们而不为每个单独的事物创建多个报告?示例:第一页显示第一个gv,第二页显示第二个gv,依此类推。当我添加一个新网格时,它不会创建一个新页面,它只是将所有内容背靠背。我希望这是有道理的,我会很乐意尝试澄清任何事情。谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

有很多图书馆可以帮助您解决这个问题。有些需要安装Office,有些则不需要。

也许试试 http://www.nuget.org/packages/ExcelGenerator

http://closedxml.codeplex.com/

答案 1 :(得分:0)

我在Aspose担任社交媒体开发人员,我们的Aspose.Cells API可以轻松实现您的要求。请参阅以下示例代码,该代码将3个不同网格视图中的数据导出到三个不同的Excel工作表:

//Create a new Workbook
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();

//Add 2 more worksheets other than default worksheet
for (int i = 1; i <= 2; i++)
{
//Add a new worksheet
workbook.Worksheets.Add();
}

//Import data from gridviews to worksheets
workbook.Worksheets[0].Cells.ImportGridView(Gridview1, 0, 0, true, false, true);
workbook.Worksheets[1].Cells.ImportGridView(Gridview2, 0, 0, true, false, true);
workbook.Worksheets[2].Cells.ImportGridView(Gridview3, 0, 0, true, false, true);

//Save the worksheet
workbook.Save("C:\\Data\\Aspose.xls");