繁体   English   中英

使用C#计算Excel中的单元格总和

[英]Calculate Sum of the cells in Excel using C#

我正在使用Windows应用程序,在该Windows应用程序中,我已将网格视图成功导出到Excel。 现在我想计算特定单元格中excel表格中单元格的总和...我尝试了一下,但是异常了...有人可以告诉我我做错了吗? 如何解决这个问题? 或告诉我任何其他解决方案。

提前致谢...

我的代码是:

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

首先,请阅读我的评论。 其次,如果您仍然从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])
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM