检索最后一列在excel中具有值

时间:2015-03-13 07:47:31

标签: c# windows excel linq linq-to-excel

我有一张有很多列的表格。假设我有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"]))));
            }

1 个答案:

答案 0 :(得分:0)

将您的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;        
}