#region 将DataGridView控件中数据导出到Excel
public bool ExportDataGridview(DataGridView gridView,bool isShowExcle)
{
if (gridView.Rows.Count == 0)
return false;
//建立Excel对象
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcle;
//生成字段名称
for (int i = 0; i < gridView.ColumnCount; i++)
{
excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < gridView.RowCount-1; i++)
{
for (int j = 0; j < gridView.ColumnCount; j++)
{
if (gridView[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + gridView[j, i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();
}
}
}
return true;
}
#endregion
添加引用Microsoft Office Excel:
using Excel = Microsoft.Office.Interop.Excel;
※在"參考"加入
using Excel = Microsoft.Office.Interop.Excel;
※在"參考"加入
调用:
if (!oper.ExportDataGridview(dgvEquiment, true))
MessageBox.Show("表格中没有数据,无法导出数据!", "系统提示", MessageBoxButtonsOK, MessageBoxIcon.Information);
if (!oper.ExportDataGridview(dgvEquiment, true))
MessageBox.Show("表格中没有数据,无法导出数据!", "系统提示", MessageBoxButtonsOK, MessageBoxIcon.Information);
沒有留言:
張貼留言