C#使用Aspose.Cells导出Excel简单实现

2022-11-25,,,,

首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net

将DataTable导出Xlsx格式的文件下载(网页输出):

 /// <summary>
/// 导出Excel表格
/// </summary>
/// <param name="list">数据集合</param>
/// <param name="header">数据表头</param>
/// <returns></returns>
public void ExportExcel(DataTable dt, string[] header)
{
Workbook wb = new Workbook(FileFormatType.Xlsx);
try
{
Worksheet sheet = wb.Worksheets[];
sheet.Name = "MO上行查询结果";
if (dt.Rows.Count <= )
{
System.Web.HttpContext.Current.Response.Write("<script>alert('没有检测到需要导出数据!');</script>");
return;
}
// 为单元格添加样式
Aspose.Cells.Style style = wb.CreateStyle();
style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center; //设置居中
style.Font.Size = ;//文字大小
style.Font.IsBold = true;//粗体
style.HorizontalAlignment = TextAlignmentType.Center;//文字居中 int rowIndex = ;
for (int i = ; i < header.Length; i++)
{
sheet.Cells[rowIndex, i].PutValue(header[i]);
sheet.Cells[rowIndex, i].SetStyle(style);
sheet.Cells.SetColumnWidth(i, );//设置宽度
}
for (int i = ; i < dt.Rows.Count; i++)//遍历DataTable行
{
sheet.Cells[i + , ].PutValue(dt.Rows[i]["SENDER"].ToString());
sheet.Cells[i + , ].PutValue(dt.Rows[i]["SENDCONTENT"].ToString());
sheet.Cells[i + , ].PutValue("");
sheet.Cells[i + , ].PutValue(dt.Rows[i]["RECDATE"].ToString());
sheet.Cells[i + , ].PutValue(dt.Rows[i]["sn"].ToString());
}
}
catch (Exception e)
{
System.Web.HttpContext.Current.Response.Write("<script>alert('导出异常:" + e.Message + "!');</script>");
}
#region 输出到Excel
using (MemoryStream ms = new MemoryStream())
{ wb.Save(ms, new OoxmlSaveOptions(SaveFormat.Xlsx));//默认支持xls版,需要修改指定版本
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
wb = null;
System.Web.HttpContext.Current.Response.End();
}
#endregion
}

Aspose.Cells.dll 下载地址:http://pan.baidu.com/s/1o8TRXDg

其它相关参考:

https://my.oschina.net/u/876556/blog/98801

http://www.cnblogs.com/top5/archive/2010/02/16/1668801.html

http://www.cnblogs.com/springyangwc/archive/2011/08/12/2136498.html

C#使用Aspose.Cells导出Excel简单实现的相关教程结束。

《C#使用Aspose.Cells导出Excel简单实现.doc》

下载本文的Word格式文档,以方便收藏与打印。