【问题标题】:Calculate Sum of the cells in Excel using C#使用C#计算Excel中单元格的总和
【发布时间】:2010-10-04 17:56:26
【问题描述】:

我正在使用 windows 应用程序,在该 windows 应用程序中,我已成功将网格视图导出到 excel。现在我想计算特定单元格中excel表中单元格的总和......我试过了,但它出现异常...... 谁能告诉我我做错了什么? 如何解决这个问题?或告诉我任何其他解决方案。

提前谢谢...

我的代码是:

wksheet.get_Range(Type.Missing, strSumOfTargetCell + RowCount).Formula = "=SUM("+strRowValue+":"+strColumnRangeValue+")";

【问题讨论】:

  • 如果您成功将gridView导出到excel,为什么还要尝试从excel读取而不是从gridview读取?

标签: c# excel


【解决方案1】:

首先,阅读我的评论。 其次,如果您仍然从 excel 计算单元格,我认为您需要编写一个代码,该代码读取 .xlsx 文件并计算一些值。这是可以读取excel doc的示例代码,并绑定到DataTable。

您的代码将是这样的。读取整个 excel 单元格后,您将获得所有单元格的值。 (当你创建 object[] row = new obejct[] 时)

using (OpenFileDialog openFileFromDialog = new OpenFileDialog())
        {
            openFileFromDialog.Filter = "Excel Document|*.xls";
            openFileFromDialog.Title = "Select FIle";
            openFileFromDialog.ShowDialog();
            if (String.IsNullOrEmpty(openFileFromDialog.FileName))
                return;

            using (OleDbConnection connection = new OleDbConnection { ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; 
                        Data Source={0};Extended Properties=Excel 12.0;", openFileFromDialog.FileName) })
            {
                    using (DbCommand command = connection.CreateCommand())
                    {
                        command.CommandText = String.Format("SELECT * FROM [{0}]", sheetName);
                        if (connection.State == ConnectionState.Closed)
                        {
                            connection.Open();
                        }
                        using (DbDataReader dr = command.ExecuteReader())
                        {

                            while (dr.Read())
                            {

                                object[] row = new object[]
                                        { 
                                        dr[1],
                                        dr[2],
                                        dr[3]
                                        };
                                YOURDATATABLE.Rows.Add(row);
                                }
                        }
                    }
                  }
            }

在yourdatatable.Rows.Add()部分,可以进行计算,而不是新建dataTable等。

decimal Sum = 0;
while(dr.Read())
{
Sum += (ConvertToDecimal(dr[1]) + ConvertToDecimal(dr[2])) * ConvertToDecimal(dr[3])
}

【讨论】:

    猜你喜欢
    • 2013-01-05
    • 2019-04-28
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多