利用不同的服务器控件将数据导出到Excel文件

<% @ Page Language = " C# "  AutoEventWireup = " true "   CodeFile = " Default.aspx.cs "  Inherits = " _Default "  EnableEventValidation = " false "   %>

<! DOCTYPE html PUBLIC  " -//W3C//DTD XHTML 1.0 Transitional//EN "   " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd " >

< html xmlns = " http://www.w3.org/1999/xhtml "   >
< head runat = " server " >
    
< title > 利用不同的服务器控件将数据导出到Excel文件 </ title >
</ head >
< body >
    
< form id = " form1 "  runat = " server " >
    
< div >
        
< asp:Button ID = " outExcelBtn "  runat = " server "  Text = " Button "  OnClick = " outExcelBtn_Click "   />
    
</ div >
    
</ form >
</ body >
</ html >
后台代码:
using  System;
using  System.Data;
using  System.Configuration;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;
using  System.Text;

public   partial   class  _Default : System.Web.UI.Page 
{
    
protected void Page_Load(object sender, EventArgs e)
    
{

    }

    
protected void outExcelBtn_Click(object sender, EventArgs e)
    
{
        
string filename = "FileFlow.xls";

        OutPutExcel(filename); 
    }


    
public void OutPutExcel(string filename)
    
{
        DataTable table 
= new DataTable();
        table.Columns.Add(
"name"typeof(string));
        table.Columns.Add(
"age"typeof(int));
        
for (int i = 0; i < 10; i++)
        
{
            DataRow row 
= table.NewRow();
            row[
"name"= "Name_" + i.ToString();
            row[
"age"= 20 + i;
            table.Rows.Add(row);
        }


        DataGrid dg 
= new DataGrid();
        dg.DataSource 
= table;
        dg.DataBind();
        

        
//定义文档类型、字符编码 
        Response.Clear();
        Response.Buffer 
= true;
        Response.Charset 
= "GB2312";
        
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开 
        
//filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc    .xls    .txt   .htm 
        Response.AppendHeader("Content-Disposition""attachment;filename=" + filename);
        Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("GB2312");
        
//Response.ContentType指定文件类型 可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html 或其他浏览器可直接支持文档 
        Response.ContentType = "application/ms-excel";
        
this.EnableViewState = false;
        
// 定义一个输入流 
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter 
= new System.Web.UI.HtmlTextWriter(oStringWriter);

        
通过Datagrid导出Excel

        
通过HTMLTable导出Excel

        
通过literal导出Excel

        
将本页内容导出为Excel

        Response.Write(oStringWriter.ToString());
        Response.End();
    }

}

你可能感兴趣的:(Excel)