1 public HttpResponseMessage ExportRecord()
2 {
3 try
4 {
5 HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
6 Workbook wb = new Workbook();
7 Worksheet sheet = wb.Worksheets[0];
8 sheet.Name = "sheetname";
9
10 List<DTO> rowList;
11
12 if (rowList.Count <= 0)
13 {
14 System.Web.HttpContext.Current.Response.Write("<script>alert('没有检测到需要导出数据!');</script>");
15 return new HttpResponseMessage();
16 }
17 List<string> header = new List<string>();
18 header = new List<string> { "列名1", "列名2", "列名3" };
19 int rowIndex = 0;
20 for (int i = 0; i < header.Count; i++)
21 {
22 sheet.Cells[rowIndex, i].PutValue(header[i]);
23 }
24
25 for (int i = 0; i < rowList.Count; i++)
26 {
27 sheet.Cells[i + 1, 0].PutValue(rowList[i].列名1);
28 sheet.Cells[i + 1, 1].PutValue(rowList[i].列名2);
29 sheet.Cells[i + 1, 2].PutValue(rowList[i].列名3.Value.ToString("yyyy-MM-dd hh:mm:ss:fff"));
30 }
31
32 #region 输出到Excel
33 using (MemoryStream ms = new MemoryStream())
34 {
35 wb.Save(ms, FileFormatType.Excel2003);
36 //两种方法
37 //方法1
38 //System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
39 //System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
40 //System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
41 //wb = null;
42 //System.Web.HttpContext.Current.Response.End();
43
44 //方法2
45 wb = null;
46 response.Content = new ByteArrayContent(ms.ToArray());
47 response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
48 response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls" };
49 }
50 #endregion
51
52 return response;
53 }
54 catch (Exception e)
55 {
56 System.Web.HttpContext.Current.Response.Write("<script>alert('导出异常:" + e.Message + "!');</script>");
57 return new HttpResponseMessage();
58 }
59 }