2012-03-06 103 views
0

我寫了一個方法,它從DataGridView獲取所有單元格並將它們複製到Excel工作簿中。保存excel文件時拋出異常

這一切工作正常和丹迪,直到我到達我實際保存它的部分。

這裏是保存它的代碼:

 //Saves the Workbook to the specified path 
     excelWorkbook.ActiveWorkbook.SaveCopyAs(pathToSave); 
     excelWorkbook.ActiveWorkbook.Saved = true; 

     //Close the workbook 
     excelWorkbook.Quit(); 

和異常被拋出:

Microsoft Office Excel cannot access the file 'C:\Users\TheGateKeeper\Desktop\New folder'. There are several possible reasons: 

• The file name or path does not exist. 
• The file is being used by another program. 
• The workbook you are trying to save has the same name as a currently open workbook. 

這是我第一次使用這個類的工作,所以我可能會搞亂的東西向上。

另外,作爲一個旁註有哪些呢:

excelWorkbook.ActiveWorkbook.Saved = true; 

嗎?

謝謝。

+0

'C:\用戶\ TheGateKeeper \桌面\新建文件夾' 是目錄。你如何設置excel文件名? – 2012-03-06 18:24:53

+0

Doh!該interlop類保存爲什麼擴展? – TheGateKeeper 2012-03-06 18:28:56

+0

1.什麼是變量pathToSave的值? 2.目錄是否存在「C:\ Users \ TheGateKeeper \ Desktop \ New文件夾」? – 2012-03-06 18:45:42

回答

1

SaveCopyAs方法的參數設置爲包含擴展名的excel文件的路徑。

例如。 C:\Users\TheGateKeeper\Desktop\TestFile.xls

擴展指定工作簿的格式,例如.xls的(2003年和<),XLSX(2007 +)

爲了您的便箋,設置保存到真正標誌的內容保存它doesn」實際上將它寫入磁盤。

要打開工作簿文件,請使用Open方法。

要將工作簿標記爲保存而不將其寫入磁盤,請將其 已保存屬性設置爲True。

首次保存工作簿時,使用SaveAs方法爲文件指定 名稱。

來源MSDN