3

I need to create and save a Excel file without inform in the code the path and file name. So I can use the savefiledialog to show the save box to input the path and file name, but I can´t use it correctly. I tried to use the worksheet.saveas but this class doesn´t show the save box to input the path and file name. How can I save a excel file with that save box?

4

1 回答 1

6

它的基本机制是这样的:

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);

这里这里有两个很棒的 Excel 使用教程。祝你好运!

于 2013-11-06T22:34:28.547 回答