2011-11-30 464 views
0

例如,我有一個電子表格excel。我想用C#閱讀它。更新單元格中的值,所有其他單元格將自動更改

在電子表格中,我有兩個或更多個小區:

A1 = 0 
B1 = A1 + 7 

是否有可能是,如果我使用C#和A1的值更改爲1,則B1細胞將被自動更新?

+0

你在做一個Excel插件或這是正在讀取Excel文件一個獨立的程序? – Flanfl

+0

它是一個讀取excel文檔的獨立程序。謝謝! – olidev

+1

它是xls還是xslx文件? –

回答

1

第二個單元格將自動更新。下面是使用MS Excel的對象模型(包括Microsoft.Interop.Excel.dll)一些代碼:

using System; 

namespace exceltest2 
{ 
    using Microsoft.Office.Interop.Excel; 

    internal class Program 
    { 
     private static void Main(string[] args) 
     { 
      Application excel = null; 
      Workbook wb = null; 
      try 
      { 
       // run Excel 
       excel = new Application(); 
       excel.Visible = false; 

       // Open file 
       wb = excel.Workbooks.Open(
        @"D:\test.xlsx", Type.Missing, false, // Read-Only? 
        Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing); 

       // Read worksheets 
       Sheets sheets = wb.Worksheets; 

       // Select worksheets 
       Worksheet ws = (Worksheet)sheets.get_Item("Table1"); 

       Range range = (Range)ws.get_Range("A1", "A1"); 

       // Check Values #1 
       Console.WriteLine(ws.get_Range("A1", "A1").Value2.ToString()); 
       Console.WriteLine(ws.get_Range("A2", "A2").Value2.ToString()); 

       range.Cells[1, 1] = 15; 

       // Check Values #2 
       Console.WriteLine(ws.get_Range("A1", "A1").Value2.ToString()); 
       Console.WriteLine(ws.get_Range("A2", "A2").Value2.ToString()); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
      } 
      finally 
      { 
       wb.Save(); 
       wb.Close(false, null, null); 
       excel.Quit(); 
       Console.ReadLine(); 
      } 
     } 
    } 
} 
+0

太棒了!按我想要的完美工作。非常感謝! – olidev

相關問題