将表中数据导出到Excel表格中
有时候,我们有将数据库中的数据导出到Excel表格中的需求,这里我就分享点心得,本人才学疏浅,若有不足之处望以指正。
不同以页面JS的导出,页面JS导出需要全部读出,且不能分页,没有标注这一功能,所以用后台C#代码导出。
1. 命名空间
using Aspose.Cells;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using Models;
using System.Drawing;
using System.Data;
//点击按钮事件
protected void btnExport_Click(object sender, EventArgs e){
Workbook workbook = new Workbook();
CommentCollection comments = workbook.Worksheets[0].Comments;//用于写标注
Entities db = new Entities();
Var bll = db.表.toList();
for (int i = 0; i < bll.Count(); i++)//行的行数
{
var obj = bll[i];
var type = obj.GetType();
var idx = 0;//列
foreach (var model in type.GetProperties())
{
var str = string.Format("{0}", model.GetValue(obj, null));
if (Regex.IsMatch(model.Name, "\\\\w+PZ"))//用于写标注
{
if (!string.IsNullOrEmpty(str) && idx > 0)
{
Comment comment = comments[comments.Add(i + 1, idx - 1)];
comment.Note = str;//和上一个数据相同的位置,将备注写进去
}
}
else
{
workbook.Worksheets[0].Cells[i + 1, idx].PutValue(str);//将值写进表格中
}
idx++;//列递增
}
}
//为标题设置样式
Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式
styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中
styleTitle.Font.Name = "宋体";//文字字体
styleTitle.Font.Size = 9;//文字大小
styleTitle.Font.IsBold = true;//粗体
for (int i = 0; i < 30; i++)
{
workbook.Worksheets[0].Cells[0, i].SetStyle(styleTitle);
}
}
//表头
workbook.Worksheets[0].Cells[0, 0].PutValue("");
workbook.Worksheets[0].Cells[0, 1].PutValue("");
workbook.Worksheets[0].Cells[0, 2].PutValue("");
workbook.Worksheets[0].Cells[0, 3].PutValue("");
workbook.Worksheets[0].Cells[0, 4].PutValue("");
workbook.Worksheets[0].Cells[0, 5].PutValue("");
workbook.Worksheets[0].Cells[0, 6].PutValue("");
workbook.Worksheets[0].Cells[0, 7].PutValue("");
//表名
string tableName = "";
if (_Id == 0)
{
tableName = "工资信息汇总表";
}
else
{
var Bpl = db.S_Department.SingleOrDefault(p => p.SDID == _Id);
if (Bpl != null)
{
tableName = Bpl.SDCName;
}
}
System.IO.MemoryStream ms = workbook.SaveToStream();
byte[] bt = ms.ToArray();
//客户端保存的文件名
string fileName = tableName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
//以字符流的形式下载文件
Response.ContentType = "application/vnd.ms-excel";
//以字符流的形式下载文件
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.BinaryWrite(bt);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
这样,我们导出的就是将数据库中表中数据导出到Excel表格中,并且带有标注。以前也尝试过用Excel的方式导出,倒是要购买,不然会限制到只能导出200行,不能满足需求。
望能给你带来一些小小的帮助。