更新单元格中的值,所有其他单元格将自动更改

本文关键字:单元格 其他 更新 | 更新日期: 2023-09-27 18:16:07

例如,我有一个电子表格excel。我想用c#来读。

在电子表格中,我有两个或多个单元格:

A1 = 0
B1 = A1 + 7

如果我使用c#将A1的值更改为1,然后B1单元格将自动更新,是否有可能?

更新单元格中的值,所有其他单元格将自动更改

第二个单元格将自动更新。下面是一些使用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();
            }
        }
    }
}

您可以使用c#在OleDbConnection, OleDbDataAdapter和DataSet的帮助下访问Excel表格。下面是一个示例,如何修改excel文件和单元格值:http://csharp.net-informations.com/excel/csharp-excel-oledb-update.htm