2016.5.11
二种方法:
前台筛选器
1.生成文件流下载
①后台接受form表单,拼接sql
public void Down(StudentI i, int Status = 0) { List<string> ls = new List<string>(); List<SqlParameter> lp = new List<SqlParameter>(); if (i.RecommName != null) { ls.Add("[email protected]"); lp.Add(new SqlParameter("@Recomm", i.Recomm)); } if (i.DateTime != 0) { ls.Add("[email protected]"); lp.Add(new SqlParameter("@DateTime", i.DateTime)); } ///取值范围 DownBLL.DownStudenI(ls, lp.ToArray(), "学员管理"); }
②利用sql查询出DataTable
public static void DownStudenI(List<string> name, SqlParameter[] parameter, string Title) { string sql = "select * from StudentI where "; foreach (var i in name) sql += i + " and "; sql += " 0=0"; DataTable dt = sd.Search(sql, parameter); ExcelHelper.CreateExcelToDown(dt, Title); }
③利用NOPI将文件写成流下载
/// <summary> /// 表转化成excel并且下载 /// </summary> /// <param name="dt">表</param> /// <param name="title">文件名</param> public static void CreateExcelToDown(DataTable dt, string title) { using (Workbook book = new HSSFWorkbook()) { Sheet sheet = book.CreateSheet("sheet1"); Row headerrow = sheet.CreateRow(0); CellStyle style = book.CreateCellStyle(); style.Alignment = HorizontalAlignment.CENTER; //1.转化表头 for (int i = 0; i < dt.Columns.Count; i++) { Cell cell = headerrow.CreateCell(i); cell.CellStyle = style; cell.SetCellValue(dt.Columns[i].ColumnName); } //2.填写数据 int RowLen = dt.Rows.Count; int ColLen = dt.Columns.Count; for (int i = 0; i < RowLen; i++) { DataRow dr = dt.Rows[i]; Row r = sheet.CreateRow((i+1)); for (int j = 0; j < ColLen; j++) { r.CreateCell(j).SetCellValue(dr[j].ToString()); } } //3.下载 using (MemoryStream ms = new MemoryStream()) { book.Write(ms); HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(title + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8))); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.End(); } } }
这个方法好在查找1边sql就可以下载,但是excel中文列名的话,我觉得就要在sql里面as比较麻烦
2.直接写Html
①查找要的所有数据
②在所有数据里面用Linq.where()查出要使用的数据
③然后把模型传入类中,生成Html代码
④然后写出网站供下载
时间: 2024-10-11 06:40:07