求gridview导出为excel问题解决
方法一:
#region 导入EXCLE功能
protected void Bt_Creat_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "UTF-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
Response.ContentEncoding = System.Text.Encoding.UTF8;
//设置输出文件类型为excel文件
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GVControl.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
#endregion
以上代码是实现将DataSet数据集导入Excel的方法。
如果出现”控件GridView必须放在带有runat=server的标记表单中”
则解决方法是:重载里面系统自带的VerifyRenderingInServerForm方法
#region 重载VerifyRenderingInServerForm方法
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
#endregion
如果你的DataSet是采用分页显示,
则采用方法二:
只能在执行 Render() 的过程中调用问题之解决方案
只能在执行 Render() 的过程中调用 RegisterForEventValidation(RegisterForEventValidation can only be called during Render(); )
当用GridView导出Execl的时候,会发生只能在执行 Render() 的过程中调用 RegisterForEventValidation的错误提示。
有两种方法可以解决以上问题:
1.修改web.config(不推荐)
2.直接在导出Execl的页面修改
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true"
CodeFile="ExportGridView.aspx.cs" Inherits="ExportGridView" %>
代码:
#region 导入EXCLE功能
protected void Bt_Creat_Click(object sender, EventArgs e)
{
GVControl.AllowPaging = false;
this.GVControl.DataSource = (DataSet)Session["DataView"];
GVControl.DataBind();
Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
//设置输出文件类型为excel文件
Response.AddHeader("Content-Disposition", "attachment;filename=FileFlow.xls");
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GVControl.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
GVControl.AllowPaging = true;
this.GVControl.DataSource = (DataSet)Session["DataView"];
GVControl.DataBind();
}
#endregion
我是winform
没接触过网页的,但是看上去不是很难理解的一段代码
DisableControls(gvhao);//设置gvhao不可用
Response.ClearContent();//清空
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");//添加查找excel文件,但是不知道为啥是addheader
Response.ContentType = "application/excel";//类型是excel
StringWriter sw = new StringWriter();//读字符串流
HtmlTextWriter htw = new HtmlTextWriter(sw);//写流
gvhao.RenderControl(htw);这句话报错
Response.Write(sw.ToString());
Response.End();
我觉得就是这样的,具体的代码没怎么写过
using System;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Diagnostics;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections;
namespace bookstore
{
/// <summary>
/// myExcel 的摘要说明。
/// </summary>
public class myExcel
{
public myExcel()
{
}
/// <summary>
/// 将DATAGRID导出为EXCEL文件方法一,
/// 参数是:要导出的DATAGRID的ID和要保存下来的EXCEL文件名
/// </summary>
/// <param name="myPage">page</param>
/// <param name="dg">datagrid</param>
/// <param name="name">filename</param>
private void OutExcel(Page myPage,DataGrid dg,string name)
{
HttpResponse Response;
Response=myPage.Response;
string name1="attachment;filename="+name+".xls";
dg.Visible=true;
Response.Clear();
Response.Buffer= true;
Response.Charset="GB2312";
Response.AppendHeader("Content-Disposition",name1);
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType ="application/ms-excel";
dg.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
dg.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
/// <summary>
/// 将DATAGRID导出为EXCEL文件方法二,
/// 参数是:要导出的DATAGRID的ID和要保存下来的EXCEL文件名
/// </summary>
/// <param name="myPage">page</param>
/// <param name="ctl">datagrid</param>
/// <param name="filename">filename</param>
public void ExportToExcel(Page myPage,DataGrid ctl,string filename)
{
HttpResponse Response;
Response=myPage.Response;
bool CurrCtlVisible=ctl.Visible;
ctl.Visible=true;
Response.AppendHeader("Content-Disposition","attachment;filename="+filename+".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.ContentType = "application/ms-excel";
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
ctl.Page.EnableViewState = true;
ctl.Visible=CurrCtlVisible;
}
private void DgOutExcel(Page myPage,DataGrid dg,string name)
{
HttpResponse Response;
Response=myPage.Response;
string name1="attachment;filename="+name+".xls";
dg.Visible=true;
Response.Clear();
Response.Buffer= true;
Response.Charset="GB2312";
Response.AppendHeader("Content-Disposition",name1);
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType ="application/ms-excel";
dg.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
dg.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
#region 导出EXCEL,用DATASET
public string myExportString(DataGrid DG,DataSet ds)
{
string HTstring="<table><tr>";
string Fieldstring="";
ArrayList myAL=new ArrayList();
string sRows="<tr>";
for(int i=0;i<DG.Columns.Count;i++)
{
HTstring+="<td>"+DG.Columns[i].HeaderText+"</td>";
Fieldstring+="<td>"+((System.Web.UI.WebControls.BoundColumn)(DG.Columns[i])).DataField+"</td>";
myAL.Add(((System.Web.UI.WebControls.BoundColumn)(DG.Columns[i])).DataField);
}
for(int k=0;k<ds.Tables[0].Rows.Count;k++)
{
foreach(string field in myAL)
{
sRows+= "<td>"+ds.Tables[0].Rows[k][field]+"</td>";
}
sRows+="</tr>";
}
HTstring+="</tr>"+sRows+"</table>";
return HTstring;
}
public void SaveToExcel(Page myPage, string myExportString,string myFileName)
{
HttpResponse resp;
resp=myPage.Response;
resp.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition","attachment;filename="+myFileName+".xls");
resp.ContentType="application/ms-excel";
resp.Write(myExportString);
resp.End();
//resp.Clear();
//resp.Close();
}
public void Export(DataGrid myDG,DataTable dt,HttpResponse response)
{
// clean up response object
response.Clear();
response.Charset = "";
response.Charset = "UTF-8";
// response.ContentEncoding = System.Text.Encoding.Default;
response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
// set response object's mime type
// response.ContentType = "application/vnd.ms-excel";
response.AppendHeader("Content-Disposition","attachment;filename=mytest.xls");
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
DataGrid dg = new DataGrid();
dg.AllowPaging = false;
dg.AllowSorting = false;
ArrayList myAL=new ArrayList();
for(int i=0;i<myDG.Columns.Count;i++)
{
// dg.Columns.AddAt(i,myDG.Columns[i]);
// dg.Columns[i].HeaderText=myDG.Columns[i].HeaderText;
myAL.Add(((System.Web.UI.WebControls.BoundColumn)(myDG.Columns[i])).DataField);
for(int k=0;k<dt.Columns.Count;k++)
{
foreach(string field in myAL)
{
if(dt.Columns[i].ColumnName==field)
{
dt.Columns[i].ColumnName=myDG.Columns[i].HeaderText;
}
}
}
}
dg.DataSource = dt;
dg.ShowHeader = true;
dg.HeaderStyle.BackColor = System.Drawing.Color.DarkGray;
dg.HeaderStyle.ForeColor = System.Drawing.Color.White;
dg.HeaderStyle.Font.Bold = true;
dg.AlternatingItemStyle.BackColor = System.Drawing.Color.LightGray;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
#endregion
}
}
我告诉你一个比较好的导出方法,用流的方式导出Excel,这个方法不用打开Excel文件,效率非常高,唯一缺点是,用流方式导出的Excel你要手动调整列宽.
System.Windows.Forms.SaveFileDialog sd = new System.Windows.Forms.SaveFileDialog();
if (!Directory.Exists(Request.PhysicalApplicationPath + "Excel\\" + Session["user"]))
Directory.CreateDirectory(Request.PhysicalApplicationPath + "Excel\\" + Session["user"]);
sd.FileName = Request.PhysicalApplicationPath + "Excel\\" + Session["user"] + "\\test.xls";
Stream myS = sd.OpenFile();
StreamWriter sw = new StreamWriter(myS, System.Text.Encoding.GetEncoding(-0));
string[] str = new string[] { "序号", "合同号", "订单号", "签订日期", "项目编号", "采购物品", "币别", "合同金额","类型", "供应商名称", "采办方式" };
string strT = "";
for (int i = 0; i < str.Length; i++)
{
strT += str[i] + "\t";
}
sw.WriteLine(strT);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string strSQL = "select * from YT_T_Contract_Items order by Contract_CN";
string strXMBH = "", strGMWP = "";
using (System.Data.DataSet dss = clsPublic.GetDs(strSQL, my_Conn))
{
System.Data.DataView dv = new System.Data.DataView(dss.Tables[0]);
dv.RowFilter = "[Contract_CN]='" + ds.Tables[0].Rows[i]["合同号"].ToString() + "'";
foreach (System.Data.DataRowView row in dv)
{
strXMBH += row["Items_CN"].ToString() + ";";
strGMWP += row["Stock_Goods"].ToString() + ";";
}
if (strXMBH != "")
strXMBH = strXMBH.Substring(0, strXMBH.Length - 1);
if (strGMWP != "")
strGMWP = strGMWP.Substring(0, strGMWP.Length - 1);
}
strT = "";
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
if (j != 0 && j!=3)
strT += ds.Tables[0].Rows[i][j].ToString() + "\t";
else if (j == 3)
{
strT += ds.Tables[0].Rows[i][j].ToString() + "\t" + strXMBH + "\t" + strGMWP + "\t";
}
else
strT += Convert.ToString(i + 1) + "\t";
}
sw.WriteLine(strT);
}
sw.Close();
myS.Close();
Response.Redirect("~/Excel/" + Session["user"].ToString() + "/test.xls");
以上代码是我从一个方法抠出来的,你组织一下,就可以了.我是从数据库数据获取的数据.
c#用GridView导出到excel,如何让导出的某一单元格的格式为数值小数单后...
你可以直接操作GridView的数据源,也就是DataTable一类的东西,然后把数据导成Excel文件
DataList套GridView 动态页面内容 导出为word文件的方法或代码_百度知 ...
1、在有页面中添加一个GridView1,添加一个button2、在页面加载事件中为GridView1填充数据3、button 控件的Click事件中添加如下代码: string style = @" .text { mso-number-format:\\@; } ";Response.Clear();Response.AddHeader("content-disposition", "attachment;filename=" + Server.UrlEncod...
gridview 导出excel 颜色问题
不知道你说的是字体颜色还是单元格填充色。如果你说的软件中不能设置,也可以在EXCEL中设置。如果指的是填充色,导出后,在EXCEL中,按CTRL+A全选当前表,再在工具中的填充颜色按钮中点选一下“无填充色”就行了。如果是指字体颜色,按上面操作后,点工具工具栏上“字体颜色”中的“自动”就行了。
gridview 导出excel
我是winform 没接触过网页的,但是看上去不是很难理解的一段代码 DisableControls(gvhao);\/\/设置gvhao不可用 Response.ClearContent();\/\/清空 Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");\/\/添加查找excel文件,但是不知道为啥是addheader Response.ContentType =...
asp.net中,gridview中的数据能不能导出成pdf格式的文件
asp.net中,gridview中的数据能不能导出成pdf格式的文件 本题只问最终结果?结果是:能
gridview 导出excel 为什么导不出来,无法显示该页,表里有2W多条数据...
试下这个。\/\/\/ \/\/\/ 绑定数据库生成XLS报表 \/\/\/ \/\/\/ 获取DataSet数据集 \/\/\/ 报表表名 private void xlsGridview(DataSet ds, string xlsName){ XlsDocument xls = new XlsDocument();int rowIndex = 1;int colIndex = 0;System.Data.DataTable table = ds.Tables[0];Worksheet sheet =...
asp.net中,gridview中的数据能不能导出成pdf格式的文件
导出到excel中 这到是可以用代码 然后使用Acrobat进行转换!至于只用代码到出成PDF有难度啊,写了两个方法给你调用 你试试 \/\/\/ \/\/\/ 将GridView的数据导入到 PDF文件 中 \/\/\/ \/\/\/ 页面的GridView \/\/\/ 默认的pdf文件名 public void GridViewDataToPdf(System.Web.UI.WebControls.GridView gdv,strin...
多个gridview怎么导出同一个Excel文档
1、你把两个GridView放在一个div里,比如这样 1 2 <gridview1 ...> 3 <gridview2 ...> 4 2、然后后台 gvSelectorder.RenderControl(oHtmlTextWriter); 这句改成divExport.RenderControl(oHtmlTextWriter); 试一下
你好,下载用Gridview导出的Excel填入数据后再导入时出现外部表不是预期...
因为你导出的不是标准的excel表 应该是html代码,你可以把你导出的excel另存为一个新的excel表 并不是所有的都可以 你试试你的行不
gridview 导出excel 不带样式
OleDbConnection conn = new OleDbConnection(execelConnectionStr);conn.Open();DataSet ds = new DataSet();OleDbDataAdapter ol = new OleDbDataAdapter("select * from [Sheet1$]", conn);DataTable table = ds.Tables.Add("execl");ol.Fill(table);DataRow[] dr = ds.Tables[0].Select();in...
恭德重酒: 引用的别人的: Gridview导出为Excel 尝试了一下Gridview导出为Excel,原本以为很简单,可是真正应用起来还是不太好弄的,呵呵,所想非所得.总结了一下应该注意下面几点: 1.由于gridview的内容可能是分页显示的,因此,这里在每次导...
抚宁县18850764195: 如何把GRIDVIEW的数据导出为EXCEL - ?
恭德重酒: 给你一个DataGrid的代码: // 导出列表信息到Excel public static void gSendGridInfoToExcel(DataGrid GridX) { Excel.Application excel= new Excel.ApplicationClass(); Excel._Workbook xBk = excel.Workbooks.Add(true); Excel._Worksheet xSt = (...
抚宁县18850764195: 怎样将gridview中的数据导出到Excel - ?
恭德重酒: 可以用openxml技术,将gridview中的数据取出来后分别赋值给cell的text属性就好了.
抚宁县18850764195: 怎么把gridview中的内容导出到excel中 - ?
恭德重酒: 如果想做复杂一点的控制,最好用别的导出方式生成xls标准格式,比如用office的 COM组件或者第三方的组件(NExcel, MyXls)等.园子里也有人做这方面的东西,你可以搜一下.
抚宁县18850764195: gridview导出excel - ?
恭德重酒: 现在,GridView中已经绑定了数据,接下来的任务就是导出到Excel.下面是button事件中的代码 Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); Response.ContentType = "...
抚宁县18850764195: 如何将gridview控件内容以excel表格导出?
恭德重酒: 朋友你可以按下面步骤试试: 导出Excel表格 Protected Sub Buttonout_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Buttonout.Click '将Gridview中的数据导出到excel中去 ' //定义文档类型、字符编码 Response.Clear() ...
抚宁县18850764195: GridView导出Excel - ?
恭德重酒: 在cs文件里面加入下面的方法public override void VerifyRenderingInServerForm(Control control) { //输出Excel文件用 }
抚宁县18850764195: 将 GridView 导出Excel?
恭德重酒:在编辑Excel模版列时将身份证号码这一列设为文本格式列
抚宁县18850764195: 如何将GridView的东西导入到EXCEL?
恭德重酒: 请问你是BS 模式还是CS模式 如果是BS模式我这里有一段代码就搞定 Response.Clear(); Response.Buffer = true; Response.Charset = "GB2312"; Response.AppendHeader("Content-Disposition", "attachment;filename=Students.xls"); ...
抚宁县18850764195: GridView导出到excel的思路即代码 - ?
恭德重酒: private void Savebutton_Click(object sender, EventArgs e) { dataGridViewToExcel(dataGridView1); } public void dataGridViewToExcel(DataGridView dgv) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Execl ...