检索最后一列的值在 excel

Retrieve last column has value in excel

我有一个 sheet,其中有很多列。假设我有以下 6 列。实际列数更多

x    temp 1 temp 2  temp 3  temp 4  temp 5  temp 6
101   22                    
102   23     34             
103   56                    
104   34     56      78       98        
105   11                    
106   12     32      43         
107   2       5      89       99     101     123

在此示例中,我想对最后一列求和,其值为 22+34+56+98+11+43+123

我使用 LinqToExcel 但不知道该怎么做。

var ff = database.Where(w => BetweenTwoDates(txt_fromDate.Text, w["Time Column"].ToString(), txt_toDate.Text) == true);
            var grouped = ff.GroupBy(row => row["Sample column"].ToString());
            foreach (var g in grouped)
            {
                X.Add(g.Key);
                var temp = g.Where(w => w["Temp "].ToString() != "");
                Y.Add(g.Sum(a => (double.Parse(a["Temp"]))));
            }

将您的 IEnumerable 转换为 DataTable 并尝试此代码,

 int _total = 0;
                foreach (DataRow _dr in dt.Rows) // Looping Rows
                {
                    int _value = 0;
                    int _colCount = 1;
                    foreach (var _column in _dr.ItemArray) // Looping Columns
                    {
                        if (_column.ToString() != "")
                        {
                          //if column value is not equal to blank , keep assign it to _value 
                           _value = Int32.Parse(_column.ToString());

                        }
                        else
                        {
                         //if column value is equal to blank , sum-up the _total with _value and break column looping and go to next row
                            _total += _value;
                            break;
                        }

                      if (_colCount == _dr.ItemArray.Length)
                        {
                            _total += _value;
                            break;
                        }
                     _colCount++;
                    }
                }

此处,dt 是您转换后的 DataTable_total 值将是您需要的结果。
希望对您有所帮助:)

编辑

这是转换为 DataTable 的方法,

   public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
        TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for(int i = 0 ; i < props.Count ; i++)
    {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;        
}