2017-02-27 96 views
2

我正在創建一個將數據寫入現有Excel文件的代碼。只有在文件關閉時它纔會讀/寫文件。如果我在文件打開時嘗試寫入文件,它將不會更改或保存文檔。在代碼運行之前或運行時打開Excel文件時,我也無法關閉工作簿(使用.close())或退出應用程序(使用.quit())。在桌面上打開**時是否可以寫入現有的Excel文件?

有沒有一種方法可以寫入Excel文件,而在我的桌面上打開並實際顯示更改?或者我可以至少關閉一個已經打開的文件讀/寫,保存並用C#代碼再次打開它?這是我正在使用的代碼;它有點無組織,但如果你運行它,你可以看到我基本上想要做的事情。請不要您必須更改要保存文件的屬地址,以便代碼正常工作(常規地址保存爲名爲excelsource的字符串變量)。代碼將首先創建一個以今天的月份和日期命名的文件(MM_YY)。它會在您每次初​​始化代碼時繼續寫入它。如果嘗試在新創建的文件處於打開狀態時寫入文件,則不會對文件應用更改(只有在文件關閉時才寫入Excel文件)。

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.OleDb; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Excel = Microsoft.Office.Interop.Excel; 
using System.Reflection; 
using System.Diagnostics; 
using System.Threading; 

namespace ConsoleApplication4 
{ 
class Program 
{ 
    static public string excelsource = @"\user\desktop\generic\"; 
    // excelsource is the "general" address of where excel file wil be saved. 
    static public bool truth; 
    static public bool truth1; 
    static public bool scan_thru = false; 
    static public int range2; 
    static public int index = 1; 
    static Excel.Application excel = new Excel.Application(); 
    static Excel.Workbook workbook; 
    static Excel.Worksheet sheet; 
    static Excel.Range range; 
    static FileInfo file; 

    static void Main(string[] args) 
    { 
     DateTime current_time = DateTime.Now; 
     string file_name = excelsource + current_time.Month.ToString() + "_" + current_time.Year.ToString() + ".xlsx"; 
     string curfile = file_name; 
     truth = File.Exists(curfile); 
     // truth determines if file exists if truth == true file exists and does not need to be created, if false a new file is created. 
     if (truth == false) 
     { 
      workbook = excel.Workbooks.Add(); 
      sheet = workbook.Sheets[1]; 
      sheet.Name = (current_time.Month.ToString() + "_" + current_time.Day + "_" + current_time.Year); 
     } 
     else 
     { 
      file = new FileInfo(file_name); 
      truth1 = IsFileinUse(file); 
      // truth1 determines if the existing file is open; truth1 == false if the file is currently closed and is true when it is open. 
      workbook = excel.Workbooks.Open(file_name); 
      sheet = workbook.Sheets[current_time.Month.ToString() + "_" + current_time.Day + "_" + current_time.Year]; 
      if (truth1 == true) 
      { 
       excel.Visible = false; 
       excel.DisplayAlerts = false; 
       workbook.Save(); 
      } 
      while (scan_thru == false & truth1 == false) 
       { 
       string box = "A" + index.ToString(); 
        range = sheet.get_Range(box, Missing.Value); 
        string range1 = range.Text; 
        bool judge = int.TryParse(range1, out range2); 
        if (judge == true) 
        { 
         index++; 
        } 
        else 
        { 
         scan_thru = true; 
        } 
       } 
       scan_thru = false; 

     } 
      int i = index; 
      while (i < (index + 100) & truth1 == false) 
      { 
       sheet.Cells[i, "A"].Value2 = i.ToString();     
       i++; 
      } 


      if (truth == false) 
      { 
       workbook.SaveAs(file_name); 
      } 
      if (truth == true & truth1 == false) 
      { 
       excel.DisplayAlerts = false; 
      } 
      index = 1; 
      workbook.Close(true); 
      excel.Quit(); 

    } 
    protected static bool IsFileinUse(FileInfo file) 
    { 
     FileStream stream = null; 

     try 
     { 
      stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
     } 
     catch (IOException) 
     { 
      return true; 
     } 
     finally 
     { 
      if (stream != null) 
       stream.Close(); 
     } 
     return false; 
    } 

} 

}

回答

1

有一個很好的機會,這是不可能的從C#應用程序執行。在Excel中打開文件時,它會阻止來自其他應用程序的寫入訪問,以便在打開的文件中保持數據完整性。這意味着你應該擁有隻讀權限。

另外,從外部應用程序強制打開和關閉任何應用程序是非常非常非常少見的更新文件的最佳方法。如果您正在修改當前打開的文件中的數據,則應該學習編寫Excel宏。

編輯1:澄清問題後:

不能添加到打開的Excel文件。但是,如果我正確理解你的問題,我認爲這將解決您的問題(我想它和它的作品對我來說):

  1. 寫信給你控制讀/寫訪問的逗號分隔的.csv文件來自您的C#應用​​程序。
  2. 在您的Excel電子表格「From Text」中添加引用.csv文件的「外部數據源」。資料來源:https://support.office.com/en-us/article/Import-or-export-text-txt-or-csv-files-5250ac4c-663c-47ce-937b-339e391393ba「通過連接到文本文件導入」部分。
  3. 在「數據」選項卡的「連接」標題下,您想要更改「屬性」以便每隔一段時間或打開文件時進行刷新。如果您不會每次更改文件名,我將取消選中「刷新時提示輸入文件名」框。

希望這對你有效。如果您需要更多解釋,請再次評論。

+1

我真的想使用Excel宏,但是我正在從傳感器收集數據並通過MODBUS tcp/Ethernet傳輸通過PLC收集的數據。我有一個庫可以在我的PC和我的PLC之間爲我執行Modbus通信,但它只能用於C#語言。因此我需要使用C#作爲中間人。我真的只需要Excel就可以存儲當天收集的數據並將其顯示到圖表中。我知道visual basic可以創建圖表,但它不能顯示我要收集的所有數據。 –

+0

謝謝,這可能證明非常有幫助。我會在今天晚些時候看看。 –

+0

對不起,打擾你,但你可以指引我一步一步地分解如何在C#中創建一個CVS文件的網站給出。 –

相關問題