zoukankan      html  css  js  c++  java
  • 将GridView导出到Excel并防止内容乱码

    我在数据库中建一个proc_ViewDriverDicpatch的储存过程,该储存过程主要完成对数据表进行交叉数据,完成交叉表功能,调用过程如下:
        public void BindData()
        
    {
            Yesidea.DAO.DbHelperSQL dbhelper 
    = new Yesidea.DAO.DbHelperSQL(new Yesidea.DAO.BaseDAO());
            SqlParameter[] parameters 
    = {
                        
    new SqlParameter("@TableName", SqlDbType.VarChar,50),
                        
    new SqlParameter("@纵轴", SqlDbType.VarChar,50),
                        
    new SqlParameter("@横轴", SqlDbType.VarChar,50),
                        
    new SqlParameter("@表体内容", SqlDbType.VarChar,20),
                        
    new SqlParameter("@是否加横向合计", SqlDbType.Bit),
                        
    new SqlParameter("@是否加纵向合计", SqlDbType.Bit)}
    ;
            parameters[
    0].Value = "ViewDicpatchDriver";
            parameters[
    1].Value = "dname";
            parameters[
    2].Value = "udept";
            parameters[
    3].Value = "mileage";
            parameters[
    4].Value = 1;
            parameters[
    5].Value = 1;
            DataSet ds 
    = dbhelper.RunProcedure("proc_ViewDriverDicpatch", parameters, "ViewDicpatchDriver");
            
    this.GridView1.DataSource = ds;
            
    this.GridView1.DataBind();
            
    this.GridView1.HeaderRow.Cells[0].Text = "司机姓名\部门";
        }

    输出为 Excel并防止文件内容乱码的代码如下:

        protected void btnExport_Click(object sender, EventArgs e)
        
    {
            Response.Clear();
            Response.AddHeader(
    "content-disposition""attachment;filename="" + Server.UrlEncode("FileName.xls"+ "");
            Response.Charset 
    = "GB2312";
            Response.ContentEncoding 
    = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
            Response.ContentType = "application/vnd.xls";
            System.IO.StringWriter stringWrite 
    = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite 
    = new HtmlTextWriter(stringWrite);

            GridView1.AllowPaging 
    = false;
            BindData();
            GridView1.RenderControl(htmlWrite);

            Response.Write(stringWrite.ToString());
            Response.End();
            GridView1.AllowPaging 
    = true;
            BindData();
        }

    注意:在页面中千万别忘了添加如下代码。

        public override void VerifyRenderingInServerForm(Control control)
        
    {
            
    // Confirms that an HtmlForm control is rendered for
        }
  • 相关阅读:
    js+canvas画随机4位验证码
    linux 下 查看 nginx 日志中访问前10 的 ip
    mysql greatest函数
    php 如何获取 post 传递的raw 数据
    php 监控文件变化 并上传到服务器
    php 如何统计本周 本月
    Yii2.0 GridView 的强大功能
    git 导出新修改的文件
    ubuntu16.04 下安装phpMyAdmin
    如何在ubuntu16.04 上搭建 phpstorm + xdebug 调试
  • 原文地址:https://www.cnblogs.com/sunfeiwto/p/1334892.html
Copyright © 2011-2022 走看看