asp.net使用MVC4框架基於NPOI作導出數據到Excel表

NPOI 是 POI 項目的 .NET 版本。POI是一個開源的Java讀寫Excel、WORD等微軟OLE2組件文檔的項目。html

使用 NPOI 你就能夠在沒有安裝 Office 或者相應環境的機器上對 WORD/EXCEL 文檔進行讀寫。NPOI是構建在POI 3.x版本之上的,它能夠在沒有安裝Office的狀況下對Word/Excel文檔進行讀寫操做。使用 NPOI 你就能夠在沒有安裝 Office 或者相應環境的機器上對 WORD/EXCEL 文檔進行讀寫。NPOI是構建在POI 3.x版本之上的,它能夠在沒有安裝Office的狀況下對Word/Excel文檔進行讀寫操做。sql

下面咱們使用NPOI在MVC4框架下製做一個導出的功能。框架

(1)在DAL數據訪問層,定義須要須要導出的數據表,能夠根據須要導出的字段,進行SQL語句的組織條件。函數

 public DataTable GetData()
        {
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ToString()))
            {
                string sql = "select [LoginID],[WageID],[Name],[UserLimit],[OnDutyTime],[CarShiFa],[OnDutyDay],[NightOnDuty],[AllNightOnDuty],[CarAllowance],[WorkOvertime],[WeekendNightWork],[WeekendOverNight] from Kaoqinsum where OnDutyTime=datename(yy,getdate()) + '-' + datename(m,dateadd(m,-1,getdate()))";
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                sda.Fill(dt);
                conn.Close();
                return dt;
            }
        }

  (2)在BLL業務邏輯層,調用數據訪問層中的GetDate();字體

  public DataTable GetDate()
        {
            return new SalaryManageDAL.KaoqinsumDAL().GetData();
        }

  (3)在控制器中,咱們來書寫導出功能的主要代碼。ui

  public ActionResult DaoChu()
          {
              DataTable dt = new SalaryManageBLL.KaoqinsumBLL().GetDate();
              //一、實例化workbook工做簿對象
              HSSFWorkbook hssfworkbook = new HSSFWorkbook();
              //二、建立文檔摘要信息
              DocumentSummaryInformation dsf = PropertySetFactory.CreateDocumentSummaryInformation();
              dsf.Company = "瀋陽工學院";//公司
              dsf.Category = "Statistics";//類別
              //CustomProperties 自定義屬性
              SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
              si.Author = "院辦";//做者
              //Comments 評論 CreateDateTime 建立時間 Template模板
              si.Keywords = "kaoqin,yuanban";//關鍵字
              si.Subject = "kaoqin";//主題
              si.Title = "考勤彙總";//標題
              si.RevNumber = "1.0";//版本號
              //三、將寫好的文檔摘要 賦值workbook對象
              hssfworkbook.DocumentSummaryInformation = dsf;
              hssfworkbook.SummaryInformation = si;
              //四、建立Sheet
              HSSFSheet Sheet1 = (HSSFSheet)hssfworkbook.CreateSheet("Sheet1");
              HSSFSheet Sheet2 = (HSSFSheet)hssfworkbook.CreateSheet("Sheet2");
              HSSFSheet Sheet3 = (HSSFSheet)hssfworkbook.CreateSheet("Sheet3");
              //五、建立頁眉頁腳
              Sheet1.CreateRow(0).CreateCell(1).SetCellValue(123);

              Sheet1.Header.Center = "統計數據";
              Sheet1.Header.Left = "logo.png";
              Sheet1.Header.Right = "zhguAddress";
              Sheet1.Footer.Center = "page";
              //六、標題
              string yeartime = time();

              HSSFCell fcell = (HSSFCell)Sheet1.CreateRow(0).CreateCell(0);//第一行
              fcell.SetCellValue("瀋陽工學院" + yeartime + "考勤彙總狀況表");//文本
              //合併單元格
              Sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 13));//2.0使用 2.0如下爲Region
              //標題樣式
              HSSFCellStyle fCellStyle = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              HSSFFont ffont = (HSSFFont)hssfworkbook.CreateFont();
              ffont.FontHeight = 20 * 20;
              ffont.FontName = "宋體";
              ffont.Color = HSSFColor.BLUE.index;
              fCellStyle.SetFont(ffont);
              fCellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.CENTER;//垂直對齊
              fCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;//水平對齊
              fcell.CellStyle = fCellStyle;


              //七、設置單元格格式 建立單元格
              /*模擬設定7列*/
              HSSFDataFormat dataformat = (HSSFDataFormat)hssfworkbook.CreateDataFormat();//數據格式
              HSSFFont font = (HSSFFont)hssfworkbook.CreateFont();//數據字體
              font.Color = HSSFColor.BLACK.index; //顏色 
              font.IsItalic = false;//斜體
              font.IsStrikeout = false;//加粗
              font.FontName = "宋體";//字體

              //必不可少 能夠變動在循環輸出數據時指定類型 須要調用sqlDbType 較複雜
              //Id  int類型
              HSSFCell cell1 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(0); //建立單元格
              HSSFCellStyle cellStyle1 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();//單元格樣式
              cellStyle1.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              // CellRangeAddressList ranglist1 = new CellRangeAddressList(0, 65535, 0, 0);//集合限定類型
              // DVConstraint constraint1 = DVConstraint.CreateNumericConstraint(DVConstraint.ValidationType.INTEGER, DVConstraint.OperatorType.BETWEEN, "0", "100");//約束
              cellStyle1.SetFont(font);
              cell1.CellStyle = cellStyle1;
              cell1.SetCellValue("");


              //Name
              HSSFCell cell2 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(1);
              HSSFCellStyle cellStyle2 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cellStyle2.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle2.SetFont(font);
              cell2.CellStyle = cellStyle2;
              cell2.SetCellValue("");


              //phone
              HSSFCell cell3 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(2);
              HSSFCellStyle cellStyle3 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cellStyle3.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle3.SetFont(font);
              cell3.CellStyle = cellStyle3;
              cell3.SetCellValue("");


              //address
              HSSFCell cell4 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(3);
              HSSFCellStyle cellStyle4 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cellStyle4.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle4.SetFont(font);
              cell4.CellStyle = cellStyle4;
              cell4.SetCellValue("");


              //Status
              HSSFCell cell5 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(4);
              HSSFCellStyle cellStyle5 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cellStyle5.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle5.SetFont(font);
              cell5.CellStyle = cellStyle5;
              cell5.SetCellValue("");


              //balance
              HSSFCell cell6 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(5);
              HSSFCellStyle cellStyle6 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cell6.SetCellValue("");
              cellStyle6.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle6.SetFont(font);
              cell6.CellStyle = cellStyle6;


              //CreateDate
              HSSFCell cell7 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(6);
              HSSFCellStyle cellStyle7 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cellStyle7.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle7.SetFont(font);
              cell7.CellStyle = cellStyle7;
              cell7.SetCellValue("");

              HSSFCell cell8 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(7);
              HSSFCellStyle cellStyle8 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cellStyle8.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle8.SetFont(font);
              cell8.CellStyle = cellStyle8;
              cell8.SetCellValue("");

              HSSFCell cell9 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(8);
              HSSFCellStyle cellStyle9 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cellStyle9.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle9.SetFont(font);
              cell9.CellStyle = cellStyle9;
              cell9.SetCellValue("");

              HSSFCell cell10 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(9);
              HSSFCellStyle cellStyle10 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cellStyle10.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle10.SetFont(font);
              cell10.CellStyle = cellStyle10;
              cell10.SetCellValue("");

              HSSFCell cell11 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(10);
              HSSFCellStyle cellStyle11 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cellStyle11.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle11.SetFont(font);
              cell11.CellStyle = cellStyle11;
              cell11.SetCellValue("");


              HSSFCell cell12 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(11);
              HSSFCellStyle cellStyle12 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cellStyle12.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle12.SetFont(font);
              cell12.CellStyle = cellStyle12;
              cell12.SetCellValue("");


              HSSFCell cell13 = (HSSFCell)Sheet1.CreateRow(1).CreateCell(12);
              HSSFCellStyle cellStyle13 = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
              cellStyle13.DataFormat = HSSFDataFormat.GetBuiltinFormat("");
              cellStyle13.SetFont(font);
              cell13.CellStyle = cellStyle13;
              cell13.SetCellValue("");

              //八、建立單元格 加入數據
              HSSFRow r = (HSSFRow)Sheet1.CreateRow(1);//第二行 標題
              for (int i = 0; i < dt.Columns.Count; i++)
              {
                  r.CreateCell(i).SetCellValue(dt.Columns[i].ToString());
              }
              if (dt.Rows.Count > 0)
              {
                  for (int i = 0; i < dt.Rows.Count; i++)
                  {
                      HSSFRow row = (HSSFRow)Sheet1.CreateRow(i + 2);//寫入行
                      for (int j = 0; j < dt.Columns.Count; j++)//寫入列
                      {
                          if (dt.Columns[j].ColumnName == "balance")
                          {
                              row.CreateCell(j).CellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");
                              row.CreateCell(j).SetCellValue(Convert.ToDouble(dt.Rows[i][j].ToString()));
                          }
                          else
                          {
                              row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
                          }
                      }
                  }
              }
              //九、求和 SUM函數
              HSSFCell cesum = (HSSFCell)Sheet1.CreateRow(Sheet1.LastRowNum + 1).CreateCell(5);//最後一行+1行等於總計行
              HSSFCell cebegin = (HSSFCell)Sheet1.GetRow(2).GetCell(5);//開始
              HSSFCell ceend = (HSSFCell)Sheet1.GetRow(Sheet1.LastRowNum - 1).GetCell(5);//結束
              cesum.SetCellFormula("sum(" + GetA_Z(5) + 3 + ":" + GetA_Z(5) + Sheet1.LastRowNum + ")");
              FileStream fs = new FileStream(Server.MapPath("~/ExportFiles/" + yeartime + "考勤信息.xls"), FileMode.Create);
              hssfworkbook.Write(fs);
              fs.Close();
              //Response.Write("導出完成");
              return View();  
              //return ;
          }

  

 public string GetA_Z(double p)
          {
              string[] str = { "0:A", "1:B", "2:C", "3:D", "4:E", "5:F", "6:G", "7:H", "8:I", "9:J", "10:K", "11:L", "12:M", "13:N", "14:O", "15:P", "16:Q", "17:R", "18:S", "19:T", "20:U", "21:V", "22:W", "23:X", "24:Y", "25:Z" };
              for (int i = 0; i < str.Length; i++)
              {
                  if (p.ToString() == str[i].Split(':')[0].ToString())
                  {
                      return str[i].Split(':')[1].ToString();
                  }
              }
              return "";
          }

  因爲實際項目中須要時間的條件限制。定義了一個返回值類型爲string的time();url

  public String time()
          {
              string time = "";
              DateTime dt = DateTime.Now;
              int year = dt.Year;
              int month = dt.Month;
              if (1 < month && 10 > month)
              {
                  time = year + "-";
                  time += "0";
                  time = time + Convert.ToString(month - 1);
              }
              if (month == 1)
              {
                  year = dt.Year - 1;
                  time = Convert.ToString(year) + "-";
                  time += "12";
              }
              return time;
          }

  (4)在前臺UI界面定義一個按鈕,來實現點擊觸發控制器中的DaoChu();spa

<a href="#" id="daochu" class="easyui-linkbutton" data-options="iconCls:'icon-search'">導出數據</a>

  定義id="daochu"所觸發的事件。code

  

  $("#daochu").click(function () {
                getdaochu = "/Kaoqinsum/DaoChu";
          //提交執行控制器的方法 initDataGrid("#dg", colums, getdaochu);
          //建立個返回值日期,用於導出時對時間的判斷,導出對應月份的數據。 var date = new Date(); var year = date.getFullYear(); var month = date.getMonth(); var clock; if (0 < month < 10) { clock = year + "-"; clock += "0"; clock += month; } if (month == 0) { year = date.getFullYear() - 1; clock = year + "-"; clock += "12"; } if ($("#OnDutyTime").datebox('getValue') != "") { geturl3 = "../ExportFiles/" + $("#OnDutyTime").datebox('getValue') + "考勤信息.xls"; ; window.open(geturl3); } if ($("#OnDutyTime").datebox('getValue') == "") { geturl2 = "../ExportFiles/" + clock + "考勤信息.xls"; window.open(geturl2); } })

  

PS:導出的Excel表下載地址http://pan.baidu.com/s/1ntp2izn   密碼:mxmoorm

相關文章
相關標籤/搜索