private void ExportButton_Click(object sender, RoutedEventArgs e)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;//许可声明
using (ExcelPackage excelPackage = new ExcelPackage())
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
DataGrid dataGrid = myDataGrid;
MessageBox.Show($"{dataGrid.Columns[2].GetCellContent(dataGrid.Items[2])?.ToString()}");
// 将数据写入单元格
for (int row = 0; row < dataGrid.Items.Count; row++)
{
for (int col = 0; col < dataGrid.Columns.Count; col++)
{
var cellValue = dataGrid.Columns[col].GetCellContent(dataGrid.Items[row])?.ToString();
worksheet.Cells[row + 1, col + 1].Value = cellValue;
}
}
for (int row = 0; row < dataGrid.Items.Count; row++)
{
for (int col = 0; col < dataGrid.Columns.Count; col++)
{
var cellValue = dataGrid.Columns[col].GetCellContent(dataGrid.Items[row])?.ToString();
worksheet.Cells[row + 1, col + 1].Value = cellValue;
}
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx";
if (saveFileDialog.ShowDialog() == true)
{
FileInfo fileInfo = new FileInfo(saveFileDialog.FileName);
excelPackage.SaveAs(fileInfo);
MessageBox.Show($"导出成功!位置在{saveFileDialog.FileName}");
}
}
}
导出excel
最新推荐文章于 2024-11-05 10:09:12 发布