我在ASP.Net网页(.Net 4.0,C#)中有一个GridView
,它有一些不可见的列。但是,用户希望这些列显示在Excel导出中。我很难过如何做到这一点。我已经尝试将其中一列添加到BoundField
和TemplateField
中,其中包含一个标签:
<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属性;它们与该列的网页上显示的内容相匹配。奇怪的是,在调试器中,单元格的Visible属性在我将其更改为true之前显示为true。我做错了什么?