/// <summary>
/// Datagridview导出Excel数据
/// </summary>
/// <param name="dgvName">控件Datagridview名称</param>
/// <param name="strFileName">导出的文件路径</param>
/// <param name="isShowExcle">是否直接打开</param>
/// <returns></returns>
public void BatchExportData(DataGridView dgvName, string strFileName, bool isShowExcle)
{
if (dgvName.Rows.Count == 0)
{
MessageBox.Show("无数据导出", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
// 创建Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
// 生成字段名称
for (int i = 0; i < dgvName.ColumnCount; i++)
{
if (dgvName.Columns[i].Visible)
{
excel.Cells[1, i + 1] = dgvName.Columns[i].HeaderText;
}
}
// 填充数据
for (int i = 0; i < dgvName.RowCount - 1; i++) //循环行
{
for (int j = 0; j < dgvName.ColumnCount; j++) //循环列
{
if (dgvName[j, i].ValueType == typeof(string))
{
if (dgvName.Rows[i].Cells[j].Visible)
{
excel.Cells[i + 2, j + 1] = "'" + Convert.ToString(dgvName.Rows[i].Cells[j].Value);
}
}
else
{
if (dgvName.Rows[i].Cells[j].Visible)
{
excel.Cells[i + 2, j + 1] = Convert.ToString(dgvName.Rows[i].Cells[j].Value);
}
}
}
}
// 设置禁止弹出保存和覆盖的询问提示框
excel.Visible = false; // 若是true,则在导出的时候会显示EXcel界面。
excel.DisplayAlerts = false;
excel.AlertBeforeOverwriting = false;
// 保存到临时工作簿
excel.Application.Workbooks.Add(true).Save();
// 保存文件
excel.Save(strFileName);
excel.Quit();
}
/// Datagridview导出Excel数据
/// </summary>
/// <param name="dgvName">控件Datagridview名称</param>
/// <param name="strFileName">导出的文件路径</param>
/// <param name="isShowExcle">是否直接打开</param>
/// <returns></returns>
public void BatchExportData(DataGridView dgvName, string strFileName, bool isShowExcle)
{
if (dgvName.Rows.Count == 0)
{
MessageBox.Show("无数据导出", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
// 创建Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
// 生成字段名称
for (int i = 0; i < dgvName.ColumnCount; i++)
{
if (dgvName.Columns[i].Visible)
{
excel.Cells[1, i + 1] = dgvName.Columns[i].HeaderText;
}
}
// 填充数据
for (int i = 0; i < dgvName.RowCount - 1; i++) //循环行
{
for (int j = 0; j < dgvName.ColumnCount; j++) //循环列
{
if (dgvName[j, i].ValueType == typeof(string))
{
if (dgvName.Rows[i].Cells[j].Visible)
{
excel.Cells[i + 2, j + 1] = "'" + Convert.ToString(dgvName.Rows[i].Cells[j].Value);
}
}
else
{
if (dgvName.Rows[i].Cells[j].Visible)
{
excel.Cells[i + 2, j + 1] = Convert.ToString(dgvName.Rows[i].Cells[j].Value);
}
}
}
}
// 设置禁止弹出保存和覆盖的询问提示框
excel.Visible = false; // 若是true,则在导出的时候会显示EXcel界面。
excel.DisplayAlerts = false;
excel.AlertBeforeOverwriting = false;
// 保存到临时工作簿
excel.Application.Workbooks.Add(true).Save();
// 保存文件
excel.Save(strFileName);
excel.Quit();
}