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


    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.
    以下代码大部分基本不用改。

    private void Export()
    {
        XlsDocument xls = new XlsDocument();
        org.in2bits.MyXls.Cell cell;
        int rowIndex = 2;
    
        xls.FileName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + HttpUtility.UrlEncode("TEST") + ".xls"; //TEST要改
        Worksheet sheet = xls.Workbook.Worksheets.AddNamed("TEST");//状态栏标题名称
        org.in2bits.MyXls.Cells cells = sheet.Cells;
    
        #region 导出Excel列宽
        ColumnInfo colInfo = new ColumnInfo(xls, sheet);
        colInfo.ColumnIndexStart = 0;
        colInfo.ColumnIndexEnd = 2;     
        colInfo.Width = 15 * 300;
        sheet.AddColumnInfo(colInfo);
        #endregion
    
        #region 表头
        MergeArea area = new MergeArea(1, 1, 1, 2); //MergeArea(int rowMin, int rowMax, int colMin, int colMax)
        org.in2bits.MyXls.Cell cellTitle = cells.AddValueCell(1, 1, "TEST");    //Excel 第一行第1到2列显示TEST
        sheet.AddMergeArea(area);
        cellTitle.Font.Height = 20 * 20;
        cellTitle.Font.Bold = true;//设置标题行的字体为粗体
        cellTitle.Font.FontFamily = FontFamilies.Roman;//设置标题行的字体为FontFamilies.Roman
        cellTitle.HorizontalAlignment = HorizontalAlignments.Centered;
    
        area = new MergeArea(2, 2, 1, 1);
        cellTitle = cells.AddValueCell(2, 1, "车号"); //第二行第一列 显示车号
        sheet.AddMergeArea(area);
        cellTitle.Font.Bold = true;
        cellTitle.Font.Height = 16 * 16;
        cellTitle.Font.FontFamily = FontFamilies.Roman;
        cellTitle.HorizontalAlignment = HorizontalAlignments.Centered;
        cellTitle.VerticalAlignment = VerticalAlignments.Centered;
        cellTitle.TopLineStyle = 1;
        cellTitle.BottomLineStyle = 1;
        cellTitle.LeftLineStyle = 1;
        cellTitle.RightLineStyle = 1;
    
        area = new MergeArea(2, 2, 2, 2);
        cellTitle = cells.AddValueCell(2, 2, "姓名");
        sheet.AddMergeArea(area);
        cellTitle.Font.Bold = true;
        cellTitle.Font.Height = 16 * 16;
        cellTitle.Font.FontFamily = FontFamilies.Roman;
        cellTitle.HorizontalAlignment = HorizontalAlignments.Centered;
        cellTitle.VerticalAlignment = VerticalAlignments.Centered;
        cellTitle.TopLineStyle = 1;
        cellTitle.BottomLineStyle = 1;
        cellTitle.LeftLineStyle = 1;
        cellTitle.RightLineStyle = 1;
    
        #endregion
    
        var list = GetList();  //获取数据
    
        for (int i = 0; i < list.Count; i++)
        {
            rowIndex++;
            cell = cells.AddValueCell(rowIndex, 1, list[i].VehicleNO);  //车号
            cell.TopLineStyle = 1;
            cell.BottomLineStyle = 1;
            cell.LeftLineStyle = 1;
            cell.RightLineStyle = 1;
    
            cell = cells.AddValueCell(rowIndex, 2, list[i].Name);   //姓名
            cell.TopLineStyle = 1;
            cell.BottomLineStyle = 1;
            cell.LeftLineStyle = 1;
            cell.RightLineStyle = 1;
    
        }
        xls.Send();
    }

    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>
  • 相关阅读:
    vim的三种模式
    vi/vim 三种模式的操作
    vim(vi)下的三种模式及其相关命令
    linux下查看最消耗CPU、内存的进程
    hdu 5288 OO’s Sequence
    宿主机mac os无法连接到虚拟机centos
    cloudstack给已有zone加入物理网络
    oracle刚開始学习的人经常使用操作100问
    七天学会ASP.NET MVC (四)——用户授权认证问题
    JEECG常见问题大全征集
  • 原文地址:https://www.cnblogs.com/cnfanhua/p/5646784.html
Copyright © 2020-2023  润新知