使用第3方组件实现导出:
private void Method(GridView GridView1)
{
org.in2bits.MyXls.XlsDocument doc = new org.in2bits.MyXls.XlsDocument();
doc.FileName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + ".xls";//excel文件名称
org.in2bits.MyXls.Worksheet sheet = doc.Workbook.Worksheets.AddNamed("sheet1");//Excel工作表名称
org.in2bits.MyXls.Cells cells = sheet.Cells;
int colnum = GridView1.Columns.Count; //获取gridview列数
for (int i = 0; i < colnum; i++)
{
cells.Add(1, (i + 1), GridView1.Columns[i].HeaderText);//导出gridView列名
}
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int j = 0; j < colnum; j++)
{
if (j == 4)
{
string a = ((Label)GridView1.Rows[i].Cells[4].FindControl("Lbl1")).Text.ToString();
cells.Add((i + 2), 5, a);
}
else if (j == 5)
{
cells.Add((i + 2), 6, ((Label)GridView1.Rows[i].Cells[5].FindControl("label1")).Text).ToString();
}
else
{
cells.Add((i + 2), (j + 1), GridView1.Rows[i].Cells[j].Text.Trim());
}
}
}
//doc.Save(@"D:\"); //保存到指定位置
doc.Send();//把写好的excel文件输出到客户端
}