网页表格抓取(Excel教程Excel函数Excel表格制作Excel2010Excel实用技巧Excel视频教程)
优采云 发布时间: 2021-11-17 08:16网页表格抓取(Excel教程Excel函数Excel表格制作Excel2010Excel实用技巧Excel视频教程)
1.首先在网页获取表单时,首先需要添加NPOI引用:
2. 添加引用后,首先要获取网页的数据源。作者的数据源是一个数据库查询返回的List。下面是具体的编码过程。
3.代码如下:
1 public void exportExcel(List movie_list)
2 {
3
4
5 ClientScript.RegisterStartupScript(this.GetType(), "message", "alert('111111111');");
6
7
8 if (movie_list == null || movie_list.Count == 0)
9 {
10
11 Response.Write("alert('没有数据要导出!');");
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电子表格导出过程基本实现了,是不是很简单?我希望你能从中学到你想学到的东西。