有兩個辦法:
第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檔案名稱”);
}