2010-09-20 80 views
0

我正在使用此代碼生成Excel文件。將導出更改爲CSV文件應該很簡單,只需修改saveAs調用中的參數即可,但不起作用。任何ideea爲什麼?使用互操作CSV導出

 Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 
     xlApp.Visible = false; 
     if (xlApp == null) 
     { 
      MessageBox.Show("EXCEL could not be started. Check that your office installation and project references are correct."); 
      return false; 
     } 
     Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet); 
     try 
     { 
      if (details != false) 
      { 
       //Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet); 
       wb.Worksheets.Add(); 
       Worksheet detailsWs = (Worksheet)wb.Worksheets[2]; 
       for (int i = 0; i < dt.Columns.Count; i++) 
       { 
        detailsWs.Cells[1, i + 1] = dt.Columns[i].Caption; 
       } 
      } 
      Worksheet ws = (Worksheet)wb.Worksheets[1]; 
      if (ws == null) 
      { 
       MessageBox.Show("Worksheet could not be created. Check that your office installation and project references are correct."); 
      } 
      for (int i = 0; i < dt.Columns.Count; i++) 
      { 
       ws.Cells[1, i + 1] = dt.Columns[i].Caption; 
      } 
      for (int i = 0; i < dt.Rows.Count; i++) 
      { 
       for (int j = 0; j < dt.Columns.Count; j++) 
       { 
        ws.Cells[i + 2, j + 1] = dt.Rows[i].ItemArray[j]; 
       } 
       worker.ReportProgress((i * 100)/dt.Rows.Count); 
      } 

      wb.SaveAs(filename, XlFileFormat.xlCSV, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 
      wb.Close(true, filename); 

      return true; 
     } 
     catch (Exception ex) 
     { 
      throw ex; 
     } 
     finally 
     { 
      // Cleanup 
      GC.Collect(); 
      GC.WaitForPendingFinalizers(); 
      GC.Collect(); 
      GC.WaitForPendingFinalizers(); 
      if (wb != null) 
      { 
       wb.Close(Type.Missing, Type.Missing, Type.Missing); 
       Marshal.FinalReleaseComObject(wb); 
      } 
      if (xlApp != null) 
      { 
       xlApp.Quit(); 
       Marshal.FinalReleaseComObject(xlApp); 
      } 
     } 
+0

定義「不起作用」。 – 2010-09-20 09:42:04

+0

它引發異常: – maephisto 2010-09-20 09:44:46

+0

這是例外:消息=「異常來自HRESULT:0x800A03EC」 – maephisto 2010-09-20 09:45:20

回答

2

XlSaveAsAccessMode.xlShared是原因。我不知道爲什麼,但我也得到了這個錯誤。 我嘗試改變XlSaveAsAccessMode.xlNoChangeXlSaveAsAccessMode.xlExclusive,

它工作!