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");
}
}
}