这是我的GridView标记.
<Columns> <asp:TemplateField HeaderText="Customer Name"> <ItemTemplate> <asp:Label ID="lblname" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Customer.Name")%>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="PickUpPoint"> <ItemTemplate> <asp:Label ID="lblPickUpPoint" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Pickuppoint")%>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns>
我有一个按钮,将值存储在excel对象的工作表单元格中.
for (int i = 0; i < GridView2.Rows.Count; i++) { for (int j = 0; j < GridView2.Rows[i].Cells.Count; j++) { xlWorkSheet.Cells[i + 1,j + 1] = GridView2.Rows[i].Cells[j].Text; } }
如何获取GridView的值并将其存储在工作表中,因为GridView2.Rows [i] .Cells [j] .Text返回空字符串.
解决方法
你缺少一个类型转换.像这样做-
Label name = (Label)GridView2.Rows[i].Cells[j].FindControl("lblname"); xlWorkSheet.Cells[i + 1,j + 1] = name.Text;
更新 – 如果您可以将标签命名为Label0和Label1,那么在第二个for循环中 –
for (int j = 0; j < GridView2.Rows[i].Cells.Count; j++) { Label xyz = (Label)GridView2.Rows[i].Cells[j].FindControl("Label"+j); xlWorkSheet.Cells[i + 1,j + 1] = xyz.Text; }
对于Header文本字符串hText = GridView2.HeaderRow.Cells [您的列号] .Text;