相关 Excel 单元格不会自动更新

发布于 2025-01-02 21:03:40 字数 931 浏览 2 评论 0原文

我编写了这个方法(在其他帖子中几乎类似)

public void update(string fileName, string sheetName)
{
    string connString = connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(fileName) + ";Extended Properties='Excel 12.0;HDR=NO'";

    try
    {
        OleDbConnection oledbConn = new OleDbConnection(connString);

        oledbConn.Open();

        OleDbCommand cmd = new OleDbCommand("UPDATE ["+sheetName+"$B5:B5] SET F1=17", oledbConn);

        cmd.ExecuteNonQuery();

        oledbConn.Close();
    }
    catch(Exception ex)
    {
        Debug.Write("Error: " + ex.Message);
    }
}

并调用该方法:

update("test.xls", "test");

到目前为止,它工作正常,因为当我打开 test.xls 文件时,B5 更新为 17。但是,如果有一个单元格:B1 依赖于 B5B1=B5*5,则 B1不会自动更新。我必须手动打开 Excel 文件并在警告的情况下保存它才能更新 B1。我怎样才能以编程方式做到这一点?

I wrote this method (almost similar in other post)

public void update(string fileName, string sheetName)
{
    string connString = connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(fileName) + ";Extended Properties='Excel 12.0;HDR=NO'";

    try
    {
        OleDbConnection oledbConn = new OleDbConnection(connString);

        oledbConn.Open();

        OleDbCommand cmd = new OleDbCommand("UPDATE ["+sheetName+"$B5:B5] SET F1=17", oledbConn);

        cmd.ExecuteNonQuery();

        oledbConn.Close();
    }
    catch(Exception ex)
    {
        Debug.Write("Error: " + ex.Message);
    }
}

and calling that method:

update("test.xls", "test");

So far, it works fine because when I open the test.xls file, B5 gets updated to 17. However, if there is a cell: B1 is dependent on B5: B1=B5*5, then B1 will not get updated automatically. I have to manually open the Excel file and save it with warning in order to get B1 updated. How can I do it programmatically?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

野却迷人 2025-01-09 21:03:40

我认为当您使用 ACE 驱动程序与 Excel 工作表交互时,您不能依赖 Excel 更新计算列。当您使用 OLEDB 操作工作簿的工作表时,它将工作表视为类似数据库表的结构。

我想您可能想要使用 OpenXML读取/写入文件。 StackOverflow 上有多个线程,其中包含有关使用 OpenXML 的更多信息,值得查看。

这篇帖子向您展示了如何使用 OpenXML 强制单元格重新计算。

I don't think that you can depend on Excel updating calculated columns when you use the ACE driver to interact with the Excel worksheet. When you are using OLEDB to operate on the workbook's worksheet, it is treating the worksheet as a database table like structure.

I think you may want to use OpenXML to read/write to the file. There are several threads on StackOverflow with more info on using OpenXML that are worth checking out.

This post shows your exactly how to force a cell re-calc using OpenXML.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文