Gridview匯出成Excel 指定顯示列

來源:互聯網
上載者:User

有兩個辦法:
第1個辦法:在匯出excel的事件中,在最前面,把Gridview中不需要輸出的列給隱藏掉(比如隱藏第1列:AbilityLicenceGrd.Columns[0].Visible = false;),

第2個辦法:直接從資料庫擷取資料而不是從gridview。你可以把資料庫取到DataTable中(取的時候過濾到不需要的列),然後把這個DataTable中的資料以http流的方式輸出到Excel

//將StringWriter 以流的形式匯出excel,excel檔案名稱為exportFileName
protected void ExcelExport(StringWriter sw, string exportFileName)
{
Response.ContentEncoding = System.Text.Encoding.GetEncoding( "GB2312 ");
//避免檔案名稱為亂碼
string fileName = HttpUtility.UrlEncode(exportFileName, Encoding.UTF8);
string str = "attachment; filename= " + fileName + ".xls ";

Response.AppendHeader( "Content-Disposition ", str);
Response.ContentType = "application/ms-excel ";
Response.Write(sw);
Response.End();
}

//將datatable中的資料進行組裝,比如添加列頭(這樣excel檔案中第一行就看到列頭名稱)
public static StringWriter GetStringWriter(DataTable dt)
{
StringWriter sw = new StringWriter();

//先寫列的表頭,這樣保證如果沒有資料也能輸出資料行表頭
sw.Write( "學號 " + "\t ");
sw.Write( "姓名 " + "\t ");
sw.Write(sw.NewLine);

//如果包含資料
if (dt != null)
{
//寫資料
foreach (DataRow dr in dt.Rows)
{
sw.Write(dr[ "StudentId "].ToString() + "\t ");
sw.Write(dr[ "StudentName "].ToString() + "\t ");
//換行
sw.Write(sw.NewLine);
}
}
sw.Close();
return sw;
}

//在頁面的匯出按鈕事件代碼
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = 根據條件從資料庫得到所要的資料(其中過濾掉不需要的列);
ExcelExport(GetStringWriter(dt), “匯出的Excel檔案名稱”);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.