1. 程式人生 > 其它 >c#操作資料庫匯出Excel表

c#操作資料庫匯出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);