【转】c# winform DataGridView导出数据到Excel中,可以导出当前页和全部数据
时间: 2024-05-16 07:18:33 浏览: 189
在C# WinForm中,可以使用DataGridView控件显示数据,并且可以将其中的数据导出到Excel中。下面是导出当前页和全部数据的示例代码:
1. 导出当前页数据:
```
// 获取DataGridView中当前显示的数据
DataTable dt = new DataTable();
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
dt.Columns.Add(column.HeaderText, column.ValueType);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dataRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dataRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dataRow);
}
// 导出数据到Excel
Excel.Application app = new Excel.Application();
Excel.Workbook workbook = app.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
workbook.SaveAs("data.xlsx");
app.Quit();
```
2. 导出全部数据:
```
// 获取DataGridView中全部数据
DataTable dt = new DataTable();
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
dt.Columns.Add(column.HeaderText, column.ValueType);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dataRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dataRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dataRow);
}
// 导出数据到Excel
Excel.Application app = new Excel.Application();
Excel.Workbook workbook = app.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
}
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
}
}
workbook.SaveAs("data.xlsx");
app.Quit();
```
需要注意的是,导出数据到Excel需要引用Microsoft.Office.Interop.Excel命名空间,因此需要在项目中添加对该命名空间的引用。
阅读全文