110,534
社区成员
发帖
与我相关
我的任务
分享
private void ExtractResult_Click(object sender, EventArgs e)
{
//由于使用的是COM库,因此有许多变量需要用Nothing 代替
Object Nothing = Missing.Value;
//WdSaveFormat 为Excel文档的保存格式
object format = Excel.XlFileFormat.xlOpenXMLWorkbook;
Excel.XlFileFormat version = Excel.XlFileFormat.xlExcel8;
SaveFileDialog saveexcel = new SaveFileDialog();
saveexcel.Filter = "文件类型(*.xlsx)|*.xlsx|文件类型(*.xls)|*.xls";
if (saveexcel.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = saveexcel.FileName;//文件路径变量
if (System.IO.Path.GetExtension(saveexcel.FileName).ToLower() == ".xlsx")
{
version = Excel.XlFileFormat.xlOpenXMLWorkbook;
}
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
try
{
Excel.Application excelApp = new Excel.Application(); //Excel应用程序变量
Excel.Workbook excelDoc = excelApp.Workbooks.Add(Nothing); //Excel文档变量
Excel.Worksheet sheet = (Excel.Worksheet)excelDoc.Sheets[1];
sheet.Cells[1, 1] = "123";
//将 excelDoc文档对象的内容保存为XLSX文档
excelDoc.SaveAs(path, Nothing, Nothing, Nothing, Nothing, Nothing, Excel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
//关闭excelDoc文档对象
excelDoc.Close(Nothing, Nothing, Nothing);
//关闭excelApp组件对象
excelApp.Quit();
MessageBox.Show(path.ToString() + " 导出成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}