当前位置:编程学习 > C#/ASP.NET >>

GridView导出生成Excel文件的问题,office2007/2010打不开 ????

导出代码

 HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=a.xls");
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        GridView1.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        GridView1.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();


用excel2003时候一切正常 
用excel2007/2010打开则提示
"您尝试打开的文件xxx.xls的格式与文件扩展名指定的格式不一致。打开文件前请验证文件没有损坏且来源可信。 是否立即打开该文件?"
选“是”后 提示“单元格数据太大” 确认后 打开的Excel文件是类似乱码的一长串字符串代码 
如“+ADw-table id+AD0AIg-tb1+ACI- style+AD0AIg-width: 800px....” --------------------编程问答-------------------- 试试这个,在某个项目中用过


private void CreateExcel(DataTable dt, string fileName)
        {
            HttpResponse resp;
            resp = Page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            string colHeaders = "", ls_item = "";

            ////定义表对象与行对象,同时用DataSet对其值进行初始化
            //DataTable dt = ds.Tables[0];
            DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
            int i = 0;
            int cl = dt.Columns.Count;

            //取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))//最后一列,加n
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                }
                else
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                }

            }
            resp.Write(colHeaders);
            //向HTTP输出流中写入取得的数据信息

            //逐行处理数据 
            foreach (DataRow row in myRow)
            {
                //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据   
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))//最后一列,加n
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }

                }
                resp.Write(ls_item);
                ls_item = "";

            }
            resp.End();
        }
--------------------编程问答--------------------  Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
  Response.ContentType = "application/vnd.xls";
  System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
打开excel模板赋值
--------------------编程问答-------------------- 这个群27102713有一个现成的代码,只需要定义参数传入DataTable就可以生成xml很简单 --------------------编程问答--------------------


 public void CreateExcel(DataSet ds, string typeid, string FileName)
    {
        HttpResponse resp;
        resp = Page.Response;
        resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
        string colHeaders = "", ls_item = "";
        int i = 0;

        //定义表对象与行对像,同时用DataSet对其值进行初始化 
        DataTable dt = ds.Tables[0];
        DataRow[] myRow = dt.Select("");
        // typeid=="1"时导出为Excel格式文件;typeid=="2"时导出为XML格式文件 
        if (typeid == "1")
        {
            //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符 
            for (i = 0; i < dt.Columns.Count - 1; i++)
            {
                colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                //colHeaders +=dt.Columns[i].Caption.ToString() +"\n"; 
            }
            colHeaders += dt.Columns[i].Caption.ToString() + "\n";
            //向HTTP输出流中写入取得的数据信息 
            resp.Write(colHeaders);
            //逐行处理数据 
            foreach (DataRow row in myRow)
            {
                //在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n 
                for (i = 0; i < dt.Columns.Count - 1; i++)
                {
                    ls_item += row[i].ToString() + "\t";
                    //ls_item += row[i].ToString() +"\n"; 
                }
                ls_item += row[i].ToString() + "\n";
                //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据 
                resp.Write(ls_item);
                ls_item = "";
            }
        }
        else
        {
            if (typeid == "2")
            {
                //从DataSet中直接导出XML数据并且写到HTTP输出流中 
                resp.Write(ds.GetXml());
            }
        }
        //写缓冲区中的数据到HTTP头文件中 
        resp.End();


    }
--------------------编程问答-------------------- 用office2003跟2007和2010的HttpContext.Current.Response.ContentType = "application/ms-excel";
这段代码不一样的吧~ --------------------编程问答-------------------- 哪天你去一个公司面试 不让用GW,不让用dataset,咋搞? --------------------编程问答-------------------- 我也遇到了同样的问题,期待大大来解决!!!!!!!! --------------------编程问答-------------------- 我给顶顶,我导出到excel的代码很简单,但是个人认为还是比较不错,就是用office2007打不开,郁闷

protected void Button8_Click(object sender, EventArgs e)//导出excel按钮
    {
        //Export("application/ms-excel", "供暖asp.xls");
        string style = "<style>td{mso-number-format:\"\\@\";}</style>";//防止导出excel时将以0开头的全数字数据的0去掉
        GridView gridview = new GridView();
        gridview.DataSource = dst;
        gridview.DataBind();  //绑定当前数据源
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        Response.AddHeader("content-disposition", "attachment; filename=focusfires.xls");
        Response.ContentType = "application/ms-excel";
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        //Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        //Response.ContentType = FileType;
        this.EnableViewState = false;
        //StringWriter tw = new StringWriter();
        //HtmlTextWriter hw = new HtmlTextWriter(tw);
        //GridView1.RenderControl(hw);
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        gridview.RenderControl(oHtmlTextWriter);
        Response.Write(style);
        Response.Write(oStringWriter.ToString());
        Response.End();
    }
--------------------编程问答-------------------- 我最近也搞过一个导出,用2007打开时也会报,不过还是可以打开的,也没乱码。

/// <summary>
        /// 导出记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            string sql = "select c.UserID as '用户名',a.UserName as '姓名',b.SchoolName as '学校',b.ZhuanYe as '专业',c.Sdate as '访问日期',c.CallPage as '页面地址',a.Email as '用户邮箱',a.Telephone as '用户联系号码' from XTGL_UserVisitDetails as c left join XTGL_UserInfo as a on c.UserID=a.UserID left join Student_Info as b on c.UserID=b.UserID where 1=1" + OutSql;
            OutSql = "";
            DataTable dt = DataAccess.GetDataTable(sql);
            string path = PubMethod.GetPath("70");
            try
            {
                ExportExcelStream(dt, HttpUtility.HtmlDecode(path + "用户访问明细.xls"));

                PubMethod.DownloadFile(Page, "用户访问明细", path + "用户访问明细.xls", ".xls");
            }
            catch (Exception)
            {
                PubMethod.ShowMessage(Page, "数据导出出错");
            }

        }

        /// <summary>
        /// 保存DataTable数据到filepath文件中
        /// </summary>
        /// <param name="table">数据源</param>
        /// <param name="filepath">文件</param>
        public void ExportExcelStream(DataTable table, string filepath)
        {
            StringWriter stringWriter = new StringWriter();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
            System.Web.UI.WebControls.DataGrid excel = new System.Web.UI.WebControls.DataGrid();
            excel.DataSource = table.DefaultView;  //输出DataTable的内容 
            excel.DataBind();
            excel.RenderControl(htmlWriter);

            string filestr = filepath;
            int pos = filestr.LastIndexOf("\\");
            string file = filestr.Substring(0, pos);
            if (!Directory.Exists(file))
            {
                Directory.CreateDirectory(file);
            }
            System.IO.StreamWriter sw = new StreamWriter(filestr);
            try
            {
                sw.Write(stringWriter.ToString());
            }
            catch (Exception)
            {
                PubMethod.ShowMessage(Page, "数据导出出错");
            }

            sw.Close();
        }

写的比较麻烦,因为需求问题。 --------------------编程问答--------------------         string style = @"<style>.text{mso-number-format:\@}</script>";//导入到excel时,保存表里数字列中前面存在的 0 .
        Response.Clear();
        Response.Charset = "GB2312";
        Response.ContentEncoding = Encoding.UTF8;
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        this.GridView1.AllowPaging = false;
        System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        this.GridView1.RenderControl(htw);
        Response.Write(style);
        Response.Write(sw.ToString());
        //Response.Write(dt.ToString());
        Response.End();

请高手检查下我的代码,用2007打开后,汉字为乱码,求解 --------------------编程问答--------------------  Response.Charset = "UTF-8";
  Response.ContentEncoding = Encoding.UTF8;
这个一定要对应,否则有时候就是乱码! --------------------编程问答--------------------  Response.Charset = "UTF-8";
  Response.ContentEncoding = Encoding.UTF8;
--------------------编程问答--------------------             Response.Charset = "GB2312";

            Response.ContentEncoding = System.Text.Encoding.UTF8;

            Response.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");

加上红颜色的这句话就好了 --------------------编程问答-------------------- 其实很简单,我刚遇到了这个问题:
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;

改为:
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

即可 --------------------编程问答-------------------- Spire.Office 2.1.1 絕對好使 --------------------编程问答-------------------- 下面这个Insus.NET已在无数据的专案中使用,暂时还没有发现用户说导出的Excel打不开或乱码等情况:
http://www.cnblogs.com/insus/articles/1400266.html --------------------编程问答--------------------
引用 14 楼  的回复:
其实很简单,我刚遇到了这个问题:
把C# code
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;


改为:
C# code
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

即可
顶,其实就是编码的问题
补充:.NET技术 ,  ASP.NET
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,