
c# 按导出按钮,将datagridview1数据导出到excel,不保存则点击取消按钮返回。大神请看下异常。
privatevoid导出_Click(objectsender,EventArgse){ExportDataGridview(dataGridView1,true);}...
private void 导出_Click(object sender, EventArgs e)
{
ExportDataGridview(dataGridView1, true);
}
public bool ExportDataGridview(DataGridView dataGridView1, bool isShowExcle)
{
if (dataGridView1.Rows.Count == 0)
{
return false;
}
//创建Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
//生成字段名称
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
//循环行
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
//循环列
{
if (dataGridView1[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + dataGridView1.Rows[i].Cells[j].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
}
//设置禁止弹出保存和覆盖的询问提示框
excel.Visible = false;
excel.DisplayAlerts = false;
excel.AlertBeforeOverwriting = false;
//保存到临时工作簿
//excel.Application.Workbooks.Add(true).Save();
//保存文件
//excel.Save("D:" + "\\234.xls");
//调出保存文件路径提示框
excel.Save();//----------------------------提示:异常来自HRESULT:Ox800A03EC
excel.Quit();
return true;
} 展开
{
ExportDataGridview(dataGridView1, true);
}
public bool ExportDataGridview(DataGridView dataGridView1, bool isShowExcle)
{
if (dataGridView1.Rows.Count == 0)
{
return false;
}
//创建Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
//生成字段名称
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
//循环行
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
//循环列
{
if (dataGridView1[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + dataGridView1.Rows[i].Cells[j].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
}
//设置禁止弹出保存和覆盖的询问提示框
excel.Visible = false;
excel.DisplayAlerts = false;
excel.AlertBeforeOverwriting = false;
//保存到临时工作簿
//excel.Application.Workbooks.Add(true).Save();
//保存文件
//excel.Save("D:" + "\\234.xls");
//调出保存文件路径提示框
excel.Save();//----------------------------提示:异常来自HRESULT:Ox800A03EC
excel.Quit();
return true;
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |