2013-01-02 145 views
0

我想使用窗体窗体生成excel文件。试图保存excel时出现错误。从BUTTOM无法保存Excel文件

方法调用

ExportToExcel(dtResult, "C:\\Excel/test.xls"); 

代码生成EXCEL

public void ExportToExcel(DataTable Tbl, string ExcelFilePath = null) 
     { 
      try 
      { 
       if (Tbl == null || Tbl.Columns.Count == 0) 
        throw new Exception("ExportToExcel: Null or empty input table!\n"); 

       // load excel, and create a new workbook 
       Excel.Application excelApp = new Excel.Application(); 
       excelApp.Workbooks.Add(); 

       // single worksheet 
       Excel._Worksheet workSheet = excelApp.ActiveSheet; 

       // column headings 
       for (int i = 0; i < Tbl.Columns.Count; i++) 
       { 
        workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName; 
       } 

       // rows 
       for (int i = 0; i < Tbl.Rows.Count; i++) 
       { 
        // to do: format datetime values before printing 
        for (int j = 0; j < Tbl.Columns.Count; j++) 
        { 
         workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j]; 
        } 
       } 

       // check fielpath 
       if (ExcelFilePath != null && ExcelFilePath != "") 
       { 
        try 
        { 
         workSheet.SaveAs(ExcelFilePath); //throws error here 
         excelApp.Quit(); 
         MessageBox.Show("Excel file saved!"); 
        } 
        catch (Exception ex) 
        { 
         throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n" 
          + ex.Message); 
        } 
       } 
       else // no filepath is given 
       { 
        excelApp.Visible = true; 
       } 
      } 
      catch (Exception ex) 
      { 
       throw new Exception("ExportToExcel: \n" + ex.Message); 
      } 
     } 

错误

System.Exception was unhandled 
    Message=ExportToExcel: 
ExportToExcel: Excel file could not be saved! Check filepath. 
Microsoft Excel cannot access the file 'C:\//5D95C000'. 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. 
    Source=Report 
    StackTrace: 
     at Report.Form1.ExportToExcel(DataTable Tbl, String ExcelFilePath) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 84 
     at Report.Form1.button1_Click(Object sender, EventArgs e) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 29 
     at System.Windows.Forms.Control.OnClick(EventArgs e) 
     at System.Windows.Forms.Button.OnClick(EventArgs e) 
     at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) 
     at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) 
     at System.Windows.Forms.Control.WndProc(Message& m) 
     at System.Windows.Forms.ButtonBase.WndProc(Message& m) 
     at System.Windows.Forms.Button.WndProc(Message& m) 
     at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) 
     at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) 
     at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) 
     at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) 
     at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) 
     at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) 
     at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) 
     at System.Windows.Forms.Application.Run(Form mainForm) 
     at Report.Program.Main() in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Program.cs:line 18 
     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
     at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Threading.ThreadHelper.ThreadStart() 
    InnerException: 
+0

更换您是否尝试过“C:\ \ Excel中“? –

+0

我试过...它没有错误地运行...但没有保存在特定路径中。 –

+0

如果在此行上放置断点,那么精确文件路径是什么workSheet.SaveAs(ExcelFilePath);?你需要确保你有一个文件路径加上一个文件名 – MethodMan

回答

1

为了让您的文件保存,你需要确保你有文件路径末尾的文件扩展名。

在这里ExportToExcel(dtResult, "C:\\Excel/test.xls");你的方法的文件路径是不正确 也确保您释放excelApp对象的正确

代替excelApp.Quit();像这样的东西

System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);