ASP.net导出Excel报表
官方站点: http://www.aspose.com/
测试环境: .net framework 2.0、Visual Studio 2005 SP2、Windows 2003。
组件下载: https://files.cnblogs.com/luck0235/Aspose.Excel.rar
//引用命名空间
using Aspose.Excel;
DataTable dt = yourFunctionGetSomeData();
if (dt.Rows.Count > 0)
{
//Excel对象
Excel excel = new Excel();
//打开模版(模板文件在rar文件中已包含,此处我放在了ThirdControls目录中命名为Template.xls)
string template = HttpRuntime.AppDomainAppPath + @"ThirdControls\Template.xls";
excel.Open(template);
//Worksheet对象
Worksheet sheet = excel.Worksheets["Sheet1"];
sheet.Name = "sheet的标题";
//Cells对象
Cells cells = sheet.Cells;
//在H1中放自己的标题
cells["H1"].PutValue(sheet.Name);
//字段的Header,此处我需放置三个字段
cells["A2"].PutValue("推荐者编号");
cells["B2"].PutValue("用户手机号");
cells["C2"].PutValue("推荐时间");
//遍历行
for (int i = 0; i < dt.Rows.Count; i++)
{
//遍历列
for (int j = 0; j < dt.Columns.Count; j++)
{
//因为H1、A2占了两行,所以需要i+2
cells[i + 2, (byte)j].PutValue(dt.Rows[i][j]);
}
}
excel.Worksheets.Add();
excel.Save(String.Format("Report{0}.xls", System.DateTime.Now.ToShortDateString()), SaveType.OpenInBrowser, FileFormatType.Default, HttpContext.Current.Response);
}
else
{
yourScript.Alert(this.Page, "抱歉,无记录!");
}
using Aspose.Excel;
DataTable dt = yourFunctionGetSomeData();
if (dt.Rows.Count > 0)
{
//Excel对象
Excel excel = new Excel();
//打开模版(模板文件在rar文件中已包含,此处我放在了ThirdControls目录中命名为Template.xls)
string template = HttpRuntime.AppDomainAppPath + @"ThirdControls\Template.xls";
excel.Open(template);
//Worksheet对象
Worksheet sheet = excel.Worksheets["Sheet1"];
sheet.Name = "sheet的标题";
//Cells对象
Cells cells = sheet.Cells;
//在H1中放自己的标题
cells["H1"].PutValue(sheet.Name);
//字段的Header,此处我需放置三个字段
cells["A2"].PutValue("推荐者编号");
cells["B2"].PutValue("用户手机号");
cells["C2"].PutValue("推荐时间");
//遍历行
for (int i = 0; i < dt.Rows.Count; i++)
{
//遍历列
for (int j = 0; j < dt.Columns.Count; j++)
{
//因为H1、A2占了两行,所以需要i+2
cells[i + 2, (byte)j].PutValue(dt.Rows[i][j]);
}
}
excel.Worksheets.Add();
excel.Save(String.Format("Report{0}.xls", System.DateTime.Now.ToShortDateString()), SaveType.OpenInBrowser, FileFormatType.Default, HttpContext.Current.Response);
}
else
{
yourScript.Alert(this.Page, "抱歉,无记录!");
}
示例结果: