我需要创建并保存Excel文件,而不在代码中通知路径和文件名。所以我可以使用savefiledialog来显示保存框以输入路径和文件名,但我无法正确使用它。 我尝试使用worksheet.saveas,但是这个类没有显示保存框来输入路径和文件名。 如何使用该保存框保存excel文件?
答案 0 :(得分:5)
它的基本机制是:
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);