【发布时间】:2016-06-22 06:04:47
【问题描述】:
您好,我将 gridview 数据导出到 excel 中,但不幸的是,导出文件中的数据不同,应该是数据表。
下面是我在导出按钮中的脚本,你能告诉我我的脚本有什么问题吗?我是 ASP.net 的新手,谢谢
try
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
int StartCol = 1;
int StartRow = 1;
int j = 0, i = 0;
//Write Headers
for (j = 0; j < GridView1.Columns.Count; j++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
myRange.Value = GridView1.Columns[j].HeaderText;
}
StartRow++;
//Write datagridview content
for (i = 0; i < GridView1.Rows.Count; i++)
{
for (j = 0; j < GridView1.Columns.Count; j++)
{
try
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];
myRange.Value2 = GridView1.Rows[i].Cells[j].Text + ";" == null ? "" : GridView1.Rows[i].Cells[j].Text + ";";
}
catch
{
GridView1.DataBind();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
// ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
// "alertMessage",
// "alert(ex.ToString());", true);
}
【问题讨论】:
-
为什么要在catch语句
GridView1.DataBind();中绑定gridview?这是唯一的地方还是你在开始这个代码块之前已经完成了,也就是在开始 excel 导出之前? Gridview 中显示的数据是否正确?导出到 Excel 之前,您是否尝试过调试并检查 gridview 中是否有数据? -
我怀疑您的
GridView没有绑定任何单元格。尝试调试并检查数据是否正确绑定到GridView。