.NET Framework操作数据库导出Excel表

首先:添加GET包:

Microsoft.Office.Interop.Excel;

其次:添加命名空间:

1using Netover.Foundation.Common;
2using Netover.Foundation.Web;
3using NPOI.HSSF.UserModel;

之后:读取数据库中导出的表(这里用的是莱姆达表达式)

IQueryable<PlanInfo> query = db.PlanInfo.Where(a => a.Isdeleted == 0);
            if (!string.IsNullOrEmpty(Request["txtUserName"])) //筛选条件
            {
                query = query.Where(a => a.Title.Contains(Request["txtUserName"]) );
            }
            if (!string.IsNullOrEmpty(Request["hidden"]))//筛选条件
            { 
query
= query.Where(a => a.Dept.ToString().Contains(Request["hidden"]));
}
 Export(query);

之后:读取Excel模板(模板附带表头)

private void Export(IQueryable<PlanInfo> query)
    {
        string path = Server.MapPath("~/Content/Templet/") + "计划审批模板.xls";
        HSSFWorkbook workbook;
        using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            workbook = new HSSFWorkbook(file);
        }
        HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);
        for (int i = 1; i < (query.Count() + 1); i++)
        {
            HSSFRow row = (HSSFRow)sheet.GetRow(i);
            //将空白行复制到下一行
            row.CopyRowTo(i + 1);
            var item = query.OrderBy(a => a.Number).Skip(i - 1).FirstOrDefault();

            #region 设置单元格的值
            HSSFCell cell1 = (HSSFCell)row.GetCell(0);
            cell1.SetCellValue(i);
            HSSFCell cell2 = (HSSFCell)row.GetCell(1);
            cell2.SetCellValue(item.Title);
            HSSFCell cell3 = (HSSFCell)row.GetCell(2);
            cell3.SetCellValue(item.ActiTypeName);
            HSSFCell cell4 = (HSSFCell)row.GetCell(3);
            cell4.SetCellValue(ConvertHelper.ConvertToString(item.BeginTime));
            HSSFCell cell5 = (HSSFCell)row.GetCell(4);
            cell5.SetCellValue(ConvertHelper.ConvertToString(item.EndTime));
            HSSFCell cell6 = (HSSFCell)row.GetCell(5);
            cell6.SetCellValue(ConvertHelper.ConvertToString(item.SiteName));
            HSSFCell cell7 = (HSSFCell)row.GetCell(6);
            cell7.SetCellValue(ConvertHelper.ConvertToString(item.stateName));
            HSSFCell cell8 = (HSSFCell)row.GetCell(7);
            cell8.SetCellValue(ConvertHelper.ConvertToString(item.Content));
            #endregion
        }
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        string filename = HttpUtility.UrlEncode(DateTime.Now.ToString("计划审批名单"));
        Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
        Response.ContentType = "application/ms-excel";
        workbook.Write(Response.OutputStream);

 

posted @ 2021-07-28 14:24  猴猴手记  阅读(258)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end