国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

如何將數據綁到gridview然后導成excel

2024-07-10 12:43:35
字體:
來源:轉載
供稿:網友
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data .SqlClient ;
using System.Data ;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String sqlconn = "Server=.; DataBase=db; Integrated Security=SSPI ";
string sql = "select top 10 * from table";

SqlConnection myConnection = new SqlConnection(sqlconn);// 創建數據庫連接實例

myConnection.Open(); //打開數據庫

SqlCommand myCommand = new SqlCommand(sql, myConnection);//創建sql的實例,執行一個sql


SqlDataAdapter Adapter = new SqlDataAdapter();//創建一個sql數據適配器
Adapter.SelectCommand = myCommand;//屬性設置為 從數據源中檢索記錄


DataSet myDs = new DataSet(); //創建數據集實例
Adapter.Fill(myDs);//填充數據集

GridView1.DataSource = myDs.Tables[0].DefaultView;//
GridView1.DataBind();

// DataToExcel("測試的cxcel", GridView1);
myConnection.Close();//關閉數據庫連接
}
public void DataToExcel(string fileName, GridView myGridView)
{
//定義文檔類型、字符編碼
Response.Clear();
Response.Buffer = false;
//Response.Charset = "utf-8";
Response.Charset = "GB2312";
//下面這行很重要, attachment 參數表示作為附件下載,您可以改成 online在線打開
//filename=FileFlow.xls 指定輸出文件的名稱,注意其擴展名和指定文件類型相符,可以為:.doc || .xls || .txt ||.htm
Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
//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.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
//定義一個輸入流
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
//將目標數據綁定到輸入流輸出
myGridView.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}

//下面這個空語句一定要加,否則會出現“必須放在具有 runat=server 的窗體標記內。”的錯誤
public override void VerifyRenderingInServerForm(Control control)
{
}

//點擊事件,生成excel
protected void Button1_Click(object sender, EventArgs e)
{
DataToExcel("測試的cxcel", GridView1);
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 湘乡市| 库车县| 昌都县| 边坝县| 利津县| 石阡县| 遂昌县| 牙克石市| 祁连县| 南京市| 雷山县| 库尔勒市| 白玉县| 广东省| 翁牛特旗| 璧山县| 吉安县| 亚东县| 曲阳县| 绥芬河市| 准格尔旗| 班戈县| 论坛| 祥云县| 泉州市| 醴陵市| 台南县| 灯塔市| 六安市| 介休市| 盐城市| 晋宁县| 鲁甸县| 双峰县| 惠东县| 扎赉特旗| 会泽县| 甘洛县| 大关县| 潞城市| 清流县|