DataGrid中的数据导入到Word和Excel_C#
2024-07-21 02:22:51
供稿:网友
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.drawing;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
using system.io;
using system.data.sqlclient ;
using system.text;
namespace datagrid_import_wordexcel
{
/// <summary>
/// 马亚红制作 2004-12-12
/// </summary>
public class webform1 : system.web.ui.page
{
protected system.web.ui.webcontrols.button btnimportword;
protected system.web.ui.webcontrols.button btn_import_excel;
protected system.web.ui.webcontrols.datagrid datagrid1;
private void page_load(object sender, system.eventargs e)
{
// 在此处放置用户代码以初始化页面
createdataset();
}
#region web 窗体设计器生成的代码
override protected void oninit(eventargs e)
{
//
// codegen: 该调用是 asp.net web 窗体设计器所必需的。
//
initializecomponent();
base.oninit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void initializecomponent()
{
this.btnimportword.click += new system.eventhandler(this.btnimportword_click);
this.btn_import_excel.click += new system.eventhandler(this.btn_import_excel_click);
this.load += new system.eventhandler(this.page_load);
}
#endregion
private void exportdatagrid(string filetype, string filename) //从datagrid导出
{
response.charset = "gb2312";
response.contentencoding = system.text.encoding.getencoding("gb2312");
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);
datagrid1.rendercontrol(hw);
response.write(tw.tostring());
response.end();
}
private void btn_import_excel_click(object sender, system.eventargs e)
{
exportdatagrid("application/ms-excel", "指数列表.xls"); //导到excel
}
private void createdataset() //建立dataset
{
dataset mydataset = new dataset("anewdataset");
datatable table1 = maketable("id", "name");
mydataset.tables.add(table1);
datagrid1.datasource=mydataset;
datagrid1.databind();
}
private datatable maketable(string c1name,string c2name) //建表
{
int i;
datatable mytable=new datatable();
datacolumn mycolumn;
// add two datacolumns
mycolumn = new datacolumn(c1name,typeof(int32)); //增加字段及设置类型
mytable.columns.add(mycolumn);
mycolumn = new datacolumn(c2name,typeof(string));
mytable.columns.add(mycolumn);
datarow dr;
for(i=1;i<11;i++) //表中增加数据
{
dr=mytable.newrow();
dr[0]=i;
dr[1]="name" + i.tostring();
mytable.rows.add(dr);
}
return mytable;
}
private void btnimportword_click(object sender, system.eventargs e) //导到word
{
exportdatagrid("application/ms-word", "指数列表.doc");
}
}
}