我需要创建并保存一个Excel文件,但不想在代码中指定路径和文件名。因此,我可以使用savefiledialog来显示保存对话框以输入路径和文件名,但我无法正确使用它。
我尝试使用worksheet.saveas,但这个类不会显示保存对话框来输入路径和文件名。
我该如何在保存时弹出保存对话框?
public void SaveExcelWorkBook()
{
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.InitialDirectory = @"C:\";
openDlg.ShowDialog();
string path = openDlg.FileName;
if (openDlg.ShowDialog() == DialogResult.OK)
{
try
{
Application excelApp = new Application();
Workbook workBook = excelApp.Workbooks.Open(path);
Worksheet workSheet = (Worksheet)workBook.Worksheets[1];
// Do your work here inbetween the declaration of your workbook/worksheet
// and the save action below.
workBook.SaveAs(/*path to save it to*/); // NOTE: You can use 'Save()' or 'SaveAs()'
workBook.Close();
}
catch (Exception ex)
{
}
}
}
我认为我还应该提到Interop对象是非托管的,所以在调用.Close()
后,您需要确保释放它们。以下是一个示例:
Marshal.ReleaseComObject(workBook);