2015-12-20 31 views
0

我的程序每小時都會進行一些數學計算並將這些結果保存到excel中。當它第一次運行(可以說上午08:00)時,它會創建一個excel工作簿和一張工作表,即「Sheet1」。它可以保存excel並釋放COM對象。到目前爲止一切都很好。如何通過使用Excel Interop添加新工作表來覆蓋現有的Excel文件 - C#

我的問題始於第二次運行(上午09:00)。當它試圖保存新的結果時,它會覆蓋現有的excel文件(這是我想要的方式),但它會覆蓋在08:00 AM創建的Sheet1。我希望它在Sheet2中保存新的結果。

在第三次運行中,我希望它將結果保存在Sheet3中
在第四次運行中,我希望它將結果保存在Sheet4中。等等等等。

我該如何更改自己的代碼才能像上面那樣做? 在此先感謝..

我的代碼:

using excelApp = Microsoft.Office.Interop.Excel; 

public static void Main(string[] arg) 
    { 
     while (true) 
     {    
      writeToExcel(); 
      int wait = 3600 * 1000; 
      System.Threading.Thread.Sleep(Convert.ToInt32(wait)); 
     } 
    } 
public static void writeToExcel() 
    { 
     excelApp.Application excl = new Microsoft.Office.Interop.Excel.Application(); 
     excl.Visible = true; 

     //MATH CALCULATIONS...... 

     excelApp.Workbook wb = excl.Workbooks.Add(excelApp.XlWBATemplate.xlWBATWorksheet); 
     excelApp.Worksheet ws1 = (excelApp.Worksheet)wb.Worksheets[1]; 
     excelApp.Worksheet ws2 = (excelApp.Worksheet)wb.Sheets.Add(); 
     excelApp.Worksheet ws3 = (excelApp.Worksheet)wb.Sheets.Add(); 
     excelApp.Worksheet ws4 = (excelApp.Worksheet)wb.Sheets.Add(); 
     excelApp.Worksheet ws5 = (excelApp.Worksheet)wb.Sheets.Add(); 
     excl.DisplayAlerts = false; 
     string fileName = string.Format(@"{0}\Data_" + DateTime.Now.Month + "-" DateTime.Now.Day + ".xlsx", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)); 
     workSheet.SaveAs(fileName); 
     Console.WriteLine("Excel Saved Successfully!!"); 

     excl.Quit(); 

     // Release COM objects 
     if (excl != null)          
     System.Runtime.InteropServices.Marshal.ReleaseComObject(excl); 

     if (workSheet != null)     
     System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet); 

     excl = null; 
     workSheet = null; 

     GC.Collect(); 
} 
+0

首先讀取舊文件,然後保存當前工作表(e xcelApp.Worksheet ws1 =(excelApp.Worksheet)wb.Worksheets [1];),然後在新的Excel文件中添加舊工作表+新工作表,你完成了! –

+0

問題是您在workSheet.SaveAs中分配的文件名。它有月份和日期,因此同一天的每次運行都將被覆蓋。你需要小時,至少...... –

回答

0

您需要從已保存的文件獲取工作簿。因此,在日常工作的開始階段,您需要一種機制來確定今天的文件是否已經存在,如果是,請使用以下內容來獲取您的工作簿。

 Workbook WB = ExcelApp.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
      Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 

希望這可以幫助您以您的方式看到錯誤。

相關問題