1.添加引用
2.将ExcelRender.cs和SqlHelper.cs两个类拷贝到App_Code文件夹下
3.写后台代码
eg:根据部门和日期导出成绩表
1 ///2 /// 点击导出Excel 3 /// 4 /// 5 /// 6 protected void Button1_Click(object sender, EventArgs e) 7 { 8 if (txtStart.Text != "" && TextBox2.Text != "") 9 {10 DataTable table = new DataTable();11 table.Columns.Add("工号", typeof(string));12 table.Columns.Add("姓名", typeof(string));13 table.Columns.Add("分数", typeof(string));14 table.Columns.Add("考试时间", typeof(string));15 table.Columns.Add("科目", typeof(string));16 17 Listlist = new List ();18 //按时间导出19 DateTime d1 = Convert.ToDateTime(txtStart.Text);20 DateTime d2 = Convert.ToDateTime(TextBox2.Text);21 //按部门导出22 var qStu = _Context.Student.Where(p => p.SBranch.ToString() == TreeView1.SelectedValue);23 if (qStu.Count() > 0)24 {25 for (int i = 0; i < qStu.Count(); i++)26 {27 var qSc = _Context.Score.Where(p=>p.SNum == qStu.ToList()[i].SNum);28 if (qSc.Count() > 0)29 {30 foreach (Score sc in qSc)31 {32 list.Add(sc);33 }34 }35 }36 }37 38 List result = new List ();39 var q = _Context.Score.Where(p => p.DateExam >= d1 && p.DateExam <= d2);40 if (q.Count() > 0)41 {42 if (TreeView1.SelectedValue == null || TreeView1.SelectedValue == "")43 {44 result = q.ToList();45 }46 else47 {48 //考试时间与部门的交集49 result = list.Intersect(q.ToList()).ToList();50 }51 for (int i = 0; i < result.Count; i++)52 {53 string a = result[i].SNum;54 //Thread.Sleep(1);55 string b = result[i].SName;56 //Thread.Sleep(1);57 string c = result[i].Scores;58 //Thread.Sleep(1);59 string d = result[i].DateExam.ToString();60 //Thread.Sleep(1);61 string e1 = result[i].SCourse;62 //Thread.Sleep(1);63 table.Rows.Add(a, b, c, d, e1);64 }65 string filename = "Mark" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//准备保存的文件名66 ExcelRender.RenderToExcel(table, Context, filename);67 }68 }69 }
附件为demo:http://pan.baidu.com/s/1gdEhWCb