我在ASP.Net網頁(.Net 4.0,C#)中有一個GridView
,它有一些不可見的列。但是,用戶希望這些列在Excel導出中顯示。我很難理解如何做到這一點。我試着讓列既是BoundField
之一,在它與標籤的TemplateField
:將GridView中不可見的列導出到Excel中
<asp:TemplateField HeaderText="Device Comments" SortExpression="DeviceComments" Visible="false">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("DeviceComments") %>' ID="lbDeviceComments" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DeviceComments" HeaderText="Device Comments" SortExpression="DeviceComments" Visible="false" />
列沒有在網頁上顯示出來,符合市場預期。但是,當我嘗試在導出到Excel的方法中使列可見時,它們保持不可見狀態。我試過了:
protected void Export2Excel(object sender, EventArgs e)
{
Response.ClearContent();
Response.AppendHeader("content-disposition", "attachment; filename=Mobile.xls");
Response.ContentType = "application/excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
GridView currentGridView = new GridView();
switch (DeviceType())
{
case "cell":
currentGridView = gvCellResults;
break;
case "loaner":
currentGridView = gvCellResults;
break;
case "wireless":
currentGridView = gvCellResults;
break;
case "smartphone":
currentGridView = gvSmartPhoneResults;
break;
}
foreach (GridViewRow gridViewRow in currentGridView.Rows)
{
gridViewRow.ForeColor = Color.Black;
HyperLink phonenumber = new HyperLink();
HyperLink imei = new HyperLink();
HyperLink employee = new HyperLink();
foreach (TableCell gridViewRowTableCell in gridViewRow.Cells)
{
phonenumber = (HyperLink)gridViewRowTableCell.FindControl("hrefPhoneNumber");
imei = (HyperLink)gridViewRow.Cells[1].FindControl("hrefIMEI");
employee = (HyperLink)gridViewRow.Cells[6].FindControl("hrefEmpName");
gridViewRowTableCell.Style["forecolor"] = "#000000";
}
gridViewRow.Cells[11].Visible = true;
gridViewRow.Cells[11].Style["display"] = "inline";
if (gridViewRow.RowType == DataControlRowType.DataRow)
{
for (int columnIndex = 0; columnIndex < gridViewRow.Cells.Count; columnIndex++)
{
gridViewRow.Cells[columnIndex].Attributes.Add("class", "text");
gridViewRow.Cells[columnIndex].Text = gridViewRow.Cells[columnIndex].Text.StripTags();
}
if (phonenumber != null)
gridViewRow.Cells[0].Text = phonenumber.Text;
if (imei != null)
gridViewRow.Cells[1].Text = imei.Text;
if (employee != null)
gridViewRow.Cells[6].Text = employee.Text;
}
}
currentGridView.RenderControl(htmlTextWriter);
string style = @"<style> .text { mso-number-format:\@; } </style> ";
Response.Write(style);
Response.Write(stringWriter.ToString());
Response.End();
}
但是該列沒有出現在Excel中。我確定我正在處理右列,因爲我已經通過調試器運行它並檢查了單元格的Text屬性;它們與該列的網頁上顯示的內容相匹配。奇怪的是,在調試器中,即使在我將其更改爲true之前,單元格的Visible屬性也顯示爲true。我究竟做錯了什麼?
您沒有提供任何解釋,你如何導出到Excel。這個答案依賴於此,請通過更新問題來提供相應的代碼。您也可以考慮大部分時間應該直接導出基礎數據,而不是導出GridView。 – mason
顯示您用於導出爲excel的代碼。我這樣做沒有問題。你應該真的在設置列(不是單元格)來顯示。我再猜,取決於你的代碼你如何使它可見或不可見 –
代碼對整個出口的方法已被添加。 – Melanie