使用winfrom简单做个界面
// 创建Excel应用程序对象
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = false;
// 创建工作簿
Excel.Workbook workbook = excelApp.Workbooks.Add(Type.Missing);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.ActiveSheet;
// 填充数据
DataTable dt = GetDataTable(); // 获取数据源
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
worksheet.Cells[i + 1, j + 1] = dt.Rows[i][j].ToString();
}
}
// 保存Excel文件
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel文件|*.xlsx";
saveFileDialog.Title = "保存Excel文件";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
workbook.SaveAs(saveFileDialog.FileName);
MessageBox.Show("导出成功!");
}
// 关闭Excel应用程序
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);