將表中數(shù)據(jù)導(dǎo)出到Excel表格中
有時(shí)候,我們有將數(shù)據(jù)庫(kù)中的數(shù)據(jù)導(dǎo)出到Excel表格中的需求,這里我就分享點(diǎn)心得,本人才學(xué)疏淺,若有不足之處望以指正。
不同以頁(yè)面JS的導(dǎo)出,頁(yè)面JS導(dǎo)出需要全部讀出,且不能分頁(yè),沒(méi)有標(biāo)注這一功能,所以用后臺(tái)C#代碼導(dǎo)出。
1. 命名空間
using Aspose.Cells;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using Models;
using System.Drawing;
using System.Data;
//點(diǎn)擊按鈕事件
protected void btnExport_Click(object sender, EventArgs e){
Workbook workbook = new Workbook();
CommentCollection comments = workbook.Worksheets[0].Comments;//用于寫(xiě)標(biāo)注
Entities db = new Entities();
Var bll = db.表.toList();
for (int i = 0; i < bll.Count(); i++)//行的行數(shù)
{
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"))//用于寫(xiě)標(biāo)注
{
if (!string.IsNullOrEmpty(str) && idx > 0)
{
Comment comment = comments[comments.Add(i + 1, idx - 1)];
comment.Note = str;//和上一個(gè)數(shù)據(jù)相同的位置,將備注寫(xiě)進(jìn)去
}
}
else
{
workbook.Worksheets[0].Cells[i + 1, idx].PutValue(str);//將值寫(xiě)進(jìn)表格中
}
idx++;//列遞增
}
}
//為標(biāo)題設(shè)置樣式
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();
//客戶(hù)端保存的文件名
string fileName = tableName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
//以字符流的形式下載文件
Response.ContentType = "application/vnd.ms-excel";
//以字符流的形式下載文件
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
//通知瀏覽器下載文件而不是打開(kāi)
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();
}
這樣,我們導(dǎo)出的就是將數(shù)據(jù)庫(kù)中表中數(shù)據(jù)導(dǎo)出到Excel表格中,并且?guī)в袠?biāo)注。以前也嘗試過(guò)用Excel的方式導(dǎo)出,倒是要購(gòu)買(mǎi),不然會(huì)限制到只能導(dǎo)出200行,不能滿(mǎn)足需求。
望能給你帶來(lái)一些小小的幫助。