1.先要引用dll文件,可以直接使用vs自带的包管理,如下图:
输入 EPPlus
我这里是安装过了的所以这里显示的是卸载而不是安装。
安装成功了之后会看到这个dll文件
代码如下:
//导出Excel
protected void BtnMemExcel_Click(object sender, EventArgs e)
{
Mem bllMember = new Mem();
int Counts = NetPagerParameter.RecordCount;
string strSql = QueryCondition();
strSql += "and Mem.MemShopID = SysShop.ShopID and Mem.MemLevelID = MemLevel.LevelID and Mem.MemUserID = SysUser.UserID";
strSql += (" and Mem.MemShopID =SysShopMemLevel.ShopID and SysShopMemLevel.MemLevelID=MemLevel.LevelID ");
DataTable db = bllMember.GetListSP(, , out Counts, PubFunction.GetShopAuthority(_UserShopID, "MemShopID", strSql)).Tables[];//将数据填充到table中 //核心代码
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet"); worksheet.Cells[, ].Value = "会员卡号";
worksheet.Cells[, ].Value = "会员姓名";
worksheet.Cells[, ].Value = "会员余额" + DateTime.Now.ToString("yyyy-MM-dd HH:mmssffff");
for (int i = ; i < db.Rows.Count + ; i++)
{
worksheet.Cells[i, ].Value = db.Rows[i - ]["MemCard"];
worksheet.Cells[i, ].Value = db.Rows[i - ]["MemName"];
worksheet.Cells[i, ].Value = db.Rows[i - ]["MemMobile"];
worksheet.Cells[i, ].Value = db.Rows[i - ]["MemBirthday"];
worksheet.Cells[i, ].Value = db.Rows[i - ]["MemPoint"];
worksheet.Cells[i, ].Value = db.Rows[i - ]["MemConsumeMoney"];
worksheet.Cells[i, ].Value = db.Rows[i - ]["ShopName"];
}
var data = package.GetAsByteArray();
//保存和归来的Excel文件作为一个ByteArray
HttpResponse response = HttpContext.Current.Response;
Response.Clear(); //输出头文件
Response.AddHeader("content-disposition", "attachment; filename=会员信息.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(data);
Response.Flush();
Response.End();
//package.Save();//这个方法是直接下载到本地
}
}