码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET之Excel下载模板、导入、导出操作

时间:2016-07-06 14:48:22      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

1.下载模板功能

  前提是服务器某文件夹中有这个文件。代码如下

 1 protected void btnDownload_Click(object sender, EventArgs e)
 2 {
 3     var path = Server.MapPath(("upfiles\\") + "test.xlt");      //upfiles-文件夹 test.xlt-文件
 4     var name = "test.xlt";
 5 
 6     try
 7     {
 8         var file = new FileInfo(path);
 9         Response.Clear();
10         Response.Charset = "GB2312";
11         Response.ContentEncoding = System.Text.Encoding.UTF8;
12         Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name)); //头信息,指定默认文件名
13         Response.AddHeader("Content-Length", file.Length.ToString());//显示下载进度
14         Response.ContentType = "application/ms-excel";     // 指定返回的是一个不能被客户端读取的流,必须被下载
15         Response.WriteFile(file.FullName);    // 把文件流发送到客户端
16             
17         HttpContext.Current.ApplicationInstance.CompleteRequest();
18     }
19     catch (Exception ex)
20     {
21         Response.Write("<script>alert(‘错误:" + ex.Message + ",请尽快与管理员联系‘)</script>");
22     }
23 }

2.导入数据

  Excel数据导入到数据库中。

 1 protected void btnImport_Click(object sender, EventArgs e)
 2 {
 3     if (FileUpload1.HasFile == false)   //判断是否包含一个文件
 4     {
 5         Response.Write("<script>alert(‘请您选择Excel文件!‘)</script>");//未上传就点击了导入按钮
 6         return;
 7     }
 8     string isXls = Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//获得文件的扩展名
 9     var extenLen = isXls.Length;
10 
11     if (!isXls.Contains(".xls"))    //判断是否 是excel文件
12     {
13         Response.Write("<script>alert(‘只可以选择Excel文件!‘)</script>");
14         return;
15     }
16 
17     string filename = FileUpload1.FileName;              //获取Excle文件名
18     string savePath = Server.MapPath(("upfiles\\") + filename);//Server.MapPath 获得虚拟服务器相对路径
19     string savePath2 = Server.MapPath(("upfiles\\"));
20 
21     if (!Directory.Exists(savePath2))   //如果不存在upfiles文件夹则创建
22     {
23         Directory.CreateDirectory(savePath2);
24     }
25     FileUpload1.SaveAs(savePath);  //SaveAs 将上传的文件内容保存在服务器上
26     var ds = ExcelSqlConnection(savePath, filename);           //将Excel转成DataSet
27     var dtRows = ds.Tables[0].Rows.Count;
28     var dt = ds.Tables[0];
29     if (dtRows == 0)
30     {
31         Response.Write("<script>alert(‘Excel表无数据!‘)</script>");
32         return;
33     }
34     try
35     {
36         for(int i = 0; i < dt.Rows.Count; i++)
37         {
38             string ve = dt.Rows[i]["车号"].ToString();
39             if (string.IsNullOrEmpty(ve))   //因数据库中车号不能为空 所以表格中车号为空的跳过这行
40             {
41                 continue;
42             }
43             //用自己的方式保存进数据库ADO/EF/...
44             var model = new TEST(); //实体
45             model.id = 1;
46             model.ve = ve;
47             model.name = dt.Rows[i]["姓名"].ToString();
48             model.Update();
49         }
50     }catch (Exception ex)
51     {
52         Response.Write("<script>alert(‘" + ex.Message + "‘)</script>");   
53     }
54     
55 }
56 
57 private DataSet ExcelSqlConnection(string savePath, string tableName)
58 {
59     //string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + savePath + ";Extended Properties=‘Excel 8.0;HDR=YES;IMEX=1‘";
60     string strCon = "Provider=Microsoft.Ace.OLEDB.12.0;" + "data source=" + savePath + ";Extended Properties=‘Excel 12.0; HDR=Yes; IMEX=1‘";    //HDR=YES Excel文件的第一行是列名而不是数据 IMEX=1可必免数据类型冲突
61     var excelConn = new OleDbConnection(strCon);
62     try
63     {
64         string strCom = string.Format("SELECT * FROM [Sheet1$]");
65         excelConn.Open();
66         OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, excelConn);
67         DataSet ds = new DataSet();
68         myCommand.Fill(ds, "[" + tableName + "$]");
69         excelConn.Close();
70         return ds;
71     }
72     catch (Exception)
73     {
74         excelConn.Close();
75         //Response.Write("<script>alert(‘" + ex.Message + "‘)</script>");
76         return null;
77     }
78 
79 }

3.导出数据到Excel中

插件采用MyXLS.
以下代码大部分基本不用改。

 1 private void Export()
 2 {
 3     XlsDocument xls = new XlsDocument();
 4     org.in2bits.MyXls.Cell cell;
 5     int rowIndex = 2;
 6 
 7     xls.FileName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + HttpUtility.UrlEncode("TEST") + ".xls"; //TEST要改
 8     Worksheet sheet = xls.Workbook.Worksheets.AddNamed("TEST");//状态栏标题名称
 9     org.in2bits.MyXls.Cells cells = sheet.Cells;
10 
11     #region 表头
12     MergeArea area = new MergeArea(1, 1, 1, 2); //MergeArea(int rowMin, int rowMax, int colMin, int colMax)
13     org.in2bits.MyXls.Cell cellTitle = cells.AddValueCell(1, 1, "TEST");    //Excel 第一行第1到2列显示TEST
14     sheet.AddMergeArea(area);
15     cellTitle.Font.Height = 20 * 20;
16     cellTitle.Font.Bold = true;//设置标题行的字体为粗体
17     cellTitle.Font.FontFamily = FontFamilies.Roman;//设置标题行的字体为FontFamilies.Roman
18     cellTitle.HorizontalAlignment = HorizontalAlignments.Centered;
19 
20     area = new MergeArea(2, 2, 1, 1);
21     cellTitle = cells.AddValueCell(2, 1, "车号"); //第二行第一列 显示车号
22     sheet.AddMergeArea(area);
23     cellTitle.Font.Bold = true;
24     cellTitle.Font.Height = 16 * 16;
25     cellTitle.Font.FontFamily = FontFamilies.Roman;
26     cellTitle.HorizontalAlignment = HorizontalAlignments.Centered;
27     cellTitle.VerticalAlignment = VerticalAlignments.Centered;
28     cellTitle.TopLineStyle = 1;
29     cellTitle.BottomLineStyle = 1;
30     cellTitle.LeftLineStyle = 1;
31     cellTitle.RightLineStyle = 1;
32 
33     area = new MergeArea(2, 2, 2, 2);
34     cellTitle = cells.AddValueCell(2, 2, "姓名");
35     sheet.AddMergeArea(area);
36     cellTitle.Font.Bold = true;
37     cellTitle.Font.Height = 16 * 16;
38     cellTitle.Font.FontFamily = FontFamilies.Roman;
39     cellTitle.HorizontalAlignment = HorizontalAlignments.Centered;
40     cellTitle.VerticalAlignment = VerticalAlignments.Centered;
41     cellTitle.TopLineStyle = 1;
42     cellTitle.BottomLineStyle = 1;
43     cellTitle.LeftLineStyle = 1;
44     cellTitle.RightLineStyle = 1;
45 
46     #endregion
47 
48     var list = GetList();  //获取数据
49 
50     for (int i = 0; i < list.Count; i++)
51     {
52         rowIndex++;
53         cell = cells.AddValueCell(rowIndex, 1, list[i].VehicleNO);  //车号
54         cell.TopLineStyle = 1;
55         cell.BottomLineStyle = 1;
56         cell.LeftLineStyle = 1;
57         cell.RightLineStyle = 1;
58 
59         cell = cells.AddValueCell(rowIndex, 2, list[i].Name);   //姓名
60         cell.TopLineStyle = 1;
61         cell.BottomLineStyle = 1;
62         cell.LeftLineStyle = 1;
63         cell.RightLineStyle = 1;
64 
65     }
66     xls.Send();
67 }

4.错误-未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序

  01.将平台换成X86

  02.安装 AccessDatabaseEngine.exe(点击下载)

5.错误-服务器无法在发送HTTP标头之后设置内容类型

  给导出按钮增加‘全局刷新‘的能力。本文例子是aspx做的

 在<asp:UpdatePanel> 标签中 增加如下代码即可

1 <Triggers>
2     <%--<asp:AsyncPostBackTrigger ControlID="" />--%> <%--局部刷新 值刷新UpdatePanel内部 --%>
3     <asp:PostBackTrigger ControlID="btnExport" /> <%--全部刷新 --%> <%--2016年7月1日 解决点击导出按钮报错“服务器无法在发送HTTP标头之后设置内容类型”的错误--%>
4 </Triggers>

 

ASP.NET之Excel下载模板、导入、导出操作

标签:

原文地址:http://www.cnblogs.com/cnfanhua/p/5646784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!