2015-10-05 101 views
0

我正在Microsoft Visual Studio中編寫一個c#WinForms應用程序。我們的數據團隊以.csv格式向我提供每日報告,並且需要以可視方式顯示結果。但是,這個程序最初是爲了處理.xlsx文件而編寫的,所以我沒有重寫所有的代碼來處理.csv文件,而是決定將文件轉換爲.xlsx會比較容易,然後將剩下的代碼保留原樣。c#Excel Interop _Workbooks.Open

因此,我修改了drawCharts()方法的第一部分,該方法負責從xlsx收集信息並將其渲染爲excel圖表。

我的研究顯示了兩種將外部文件讀入Excel工作簿的方法,第一種使用Workbooks.Open,第二種使用Workbooks.OpenText。

這裏是我的代碼:

private void drawCharts() 
    { 
     //Declare variables for use 
     //These first three values are going to be used later and can be ignored. 
     Excel.Application xlApp = null; 
     Excel.Workbook xlWorkbook = null; 
     Excel.Worksheet xlWorksheet = null; 
     object misValue = System.Reflection.Missing.Value; 

     string path = "\\\\Data\\Departmental Data\\TechSupport\\_Report" 

     //define the actual file path. Separate because I use the path variable elsewhere 
     string source = Path.Combine(path, "report.csv"); 

     //define the destination file. Using Environment.UserName so multiple people can run this program at the same time, all using unique files except when they first load. There's probably a better way of doing this. 
     string use = Path.Combine(path, "Report-" + Environment.UserName + ".xlsx"); 

     //A boolean telling the program to exit if there was an error 
     bool shouldExit = false; 
     Excel.Application app = null; //Temporary application used for opening the csv 

     try 
     { 
      MessageBox.Show("Opening file " + source); 
      app = new Excel.Application(); 
      Excel.Workbook wb = app.Workbooks.Open(source); //source points to the csv. This is the line that fails. 
      MessageBox.Show(String.Format("Saving {0} as {1}", source, use)); 
      wb.SaveAs(use, Excel.XlFileFormat.xlOpenXMLWorkbook); 
      wb.Close(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
      shouldExit = true; 
     } 
     finally 
     { 
      if (app != null) { app.Quit(); } 
      releaseObject(app); 
      if (shouldExit) { Environment.Exit(1); } 
     } 

     //Rest of the code... 
} 

出錯行是Excel.Workbook wb = app.Workbooks.Open(source);。執行此行時,Excel會引發錯誤,指出無法打開文件,因爲找不到該文件。研究這個,我發現this article其中說我應該將其更改爲Excel.Workbook wb = app.Workbooks.OpenText(source)。但是,這隻會導致編譯器錯誤,說明Cannot implicitly convert type 'void' to 'Microsoft.Office.Interop.Excel.Workbook'

任何想法,將不勝感激。

+0

爲什麼不編寫代碼來處理.csv?這些是一些最簡單的文件(假設它們設置得很好)。 –

+0

這也會起作用。不幸的是,我有另一個問題。其中一個字段是其中包含文本名稱的列,因此我得到了「business,Inc.」,這當然會變成兩列,而不是保留爲一個。我將不得不與我們的數據團隊交談,看看他們是否可以在本專欄中添加雙引號,或者(對我來說更簡單),如果他們可以導出爲.xlsx。 –

+0

*該文件無法打開,因爲找不到它。*這是不言而喻的 –

回答

0

所以,經過一些研究,我發現我的錯誤。文件路徑已更改,因爲.csv所在的文件夾已重命名。在檢查文件路徑是否正確時,我一直在查看我的測試目錄而不是生產目錄,因此所有內容出現正確。

它總是這些小東西....