问题描述
Microsoft.Office.Interop.Excel.ApplicationapplExcel=newMicrosoft.Office.Interop.Excel.ApplicationClass();Microsoft.Office.Interop.Excel.WorkbookxlWorkbook;Microsoft.Office.Interop.Excel.WorksheetxlWorksheet;System.Reflection.MissingoMissing=System.Reflection.Missing.Value;try{applExcel.Visible=true;xlWorkbook=applExcel.Workbooks.Add(oMissing);xlWorksheet=(Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Worksheets.Add(oMissing,oMissing,1,oMissing);xlWorksheet.Name="NewWorksheet";xlWorksheet.Cells[1,1]="Topic:";xlWorksheet.Cells[1,2]=".NetInteropExcelDemo";xlWorkbook.SaveAs(saveAsPath,oMissing,oMissing,oMissing,oMissing,oMissing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared,oMissing,oMissing,oMissing,oMissing,oMissing);applExcel.Quit();}catch(System.Exceptionex){//showError(ex.Message);}finally{System.Runtime.InteropServices.Marshal.ReleaseComObject(applExcel);xlWorksheet=null;xlWorkbook=null;applExcel=null;GC.Collect();}保存于其他盘都可以,唯独保存于桌面时会出错???
解决方案
解决方案二:
这种问题好象是因为桌面的文件夹路径中存在空格(比如DocumentsandSettings中间就有空格,可能把这个空格用其他字符替换了),所以导致。我怀疑这个应该是个Bug。
解决方案三:
參考:Excel.ApplicationappExcel=null;Excel._Workbookworkbook=null;Excel._WorksheetworksheetGrid=null;try{SaveFileDialogdlg=newSaveFileDialog();dlg.InitialDirectory="D:\";dlg.Filter="Excel文件|*.xls";dlg.DefaultExt="xls";dlg.AddExtension=true;dlg.OverwritePrompt=false;dlg.Title="導出Excel文件,請指定路徑(操作員在此路徑需要有寫入權限),同時輸入文件名";stringfileName=string.Empty;if(dlg.ShowDialog()==DialogResult.OK){fileName=dlg.FileName;if(fileName!=string.Empty){//狀態信息this.Cursor=Cursors.WaitCursor;appExcel=newExcel.ApplicationClass();workbook=appExcel.Workbooks.Add(Type.Missing);worksheetGrid.Activate();appExcel.ActiveWindow.Zoom=75;//刪除多余的sheetExcel.Worksheetworksheet2=(Excel.Worksheet)workbook.Worksheets.get_Item(2);Excel.Worksheetworksheet3=(Excel.Worksheet)workbook.Worksheets.get_Item(3);worksheet2.Delete();worksheet3.Delete();//處理數據進入Excel--this.ExportData(worksheetGrid,mView);appExcel.ActiveWorkbook.SaveAs(fileName,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Excel.XlSaveAsAccessMode.xlExclusive,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);MessageBox.Show("導出成功,文件位于:"+fileName+"");worksheetGrid=null;workbook=null;appExcel.Quit();appExcel=null;}}