首页 > 技术文章 > 网页表格转化为Excel文档

SunshineAgain 2016-07-20 09:14 原文

  1.首先,获取网页上表格的时候,首先我们需要添加NPOI引用:

      

 

  2.添加引用后,先要获取网页的数据源,笔者的数据源是通过数据库查询返回的一个List<Movie>,下面就开始就是具体的编代码过程。

 

  3.代码如下:

 1 public void exportExcel(List<Movie> movie_list)
 2         {
 3 
 4 
 5             ClientScript.RegisterStartupScript(this.GetType(), "message", "<script>alert('111111111');</script>");
 6 
 7 
 8             if (movie_list == null || movie_list.Count == 0)
 9             {
10 
11                 Response.Write("<script>alert('没有数据要导出!');</script>");
12                 return;
13             }
14 
15             //定义表头数组
16             string[] excelHead = { "序号","名称", "地点", "票房" };
17 
18             //自定义表头
19             var workBook = new HSSFWorkbook();
20             var sheet = workBook.CreateSheet("电影数据");
21             var col = sheet.CreateRow(0);
22             //遍历表头在exal表格中
23             for (int i = 0; i < excelHead.Length; i++)
24             {
25                 //报表的头部
26                 col.CreateCell(i).SetCellValue(excelHead[i]);
27             }
28             int a = 1;
29             //遍历表数据
30             foreach (var item in movie_list)
31             {
32                 var row = sheet.CreateRow(a);
33                 row.CreateCell(0).SetCellValue(a);
34                 row.CreateCell(1).SetCellValue(item.MovieName);
35                 row.CreateCell(2).SetCellValue(item.MovieLocat);
36                 row.CreateCell(3).SetCellValue(item.MoviePrice);
37                 a++;
38             }
39        
40             string File_name = "电影统计-"+DateTime.Now.ToString("yyMMddHHmmss")+".xls";
41             var file = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Exports\\" + File_name, FileMode.Create);
42             workBook.Write(file);
43             file.Close();
44              /*
45              * 最后重定向到项目下的Export文件夹内的Excel文件,
46              * 网页会直接提示我们下载。如果是想要在网页生成超链接,
47              * 也可以这样写:Response.Write(file);
48              */
49             Response.Redirect("/Exports/" + File_name);
50 
51         }
52     }                                                                           

  

  4.最后在网页下载文件截图:

 

      

 

 

5.一个完整的Excel表格导出过程基本上就实现了,是不是还挺简单呢。希望大家可以从中学到自己想要学到的东西。

推荐阅读