2
我使用Linq with DataSet for excel多張表。 如何使用LINQ組進行分組?如何使用「LINQ組」?
示例數據:
Name | Rate | Date | Code | ROW_SEQ
A | 12 | 01/01/2015 | 12 | 1
B | 13 | 01/01/2015 | 12 | 2
Sub Total | 25 | 01/01/2015 | 12 |
C | 10 | 01/01/2015 | 12 | 3
Grand Total | 35 | 01/01/2015 | 12 |
D | 15 | 10/01/2015 | 15 | 1
E | 16 | 10/01/2015 | 15 | 2
Sub Total | 31 | 10/01/2015 | 15 |
F | 10 | 10/01/2015 | 15 | 3
Grand Total | 41 | 10/01/2015 | 15 |
C#代碼:
protected void btnExportExcel_Click(object sender, EventArgs e)
{
/*== How to use Group by LINQ? ==*/
DataSet dsTmp = new DataSet();
DataTable dtTmp = dtExport.Copy();
var grouped = from table in dtTmp.AsEnumerable()
group table by new { date_Col = table["date"] , code_Col = table["code"] } into groupby
select new
{
Value = groupby.Key,
ColumnValues = groupby
};
/*== How to use Group by LINQ? ==*/
foreach (var key in grouped)
{
dtTmp = new DataTable();
dtTmp = dtExport.Clone();
dtTmp.TableName = (key.Value.settle_date_Col + "-" + key.Value.bank_code_Col).Replace("00:00:00", "").Replace("/","");
foreach (var rw in key.ColumnValues)
{
dtTmp.ImportRow(rw);
}
dtTmp.AcceptChanges();
dsTmp.Tables.Add(dtTmp.Copy());
}
dsTmp.AcceptChanges();
string fileName = string.Format("{0}_{1}.xls", this._ID, DateTime.Now.ToString("yyyyMMdd_HHmmss"));
ExcelMultiSheet.ToExcel(dsTmp, fileName, Page.Response);
}
代碼結果:
Sheet1
Name | Rate | Date | Code | ROW_SEQ
A | 12 | 01/01/2015 | 12 | 1
B | 13 | 01/01/2015 | 12 | 2
C | 10 | 01/01/2015 | 12 | 3
Sheet2
Name | Rate | Date | Code | ROW_SEQ
Sub Total | 25 | 01/01/2015 | 12 |
Grand Total | 35 | 01/01/2015 | 12 |
Sheet3
Name | Rate | Date | Code | ROW_SEQ
D | 15 | 10/01/2015 | 15 | 1
E | 16 | 10/01/2015 | 15 | 2
F | 10 | 10/01/2015 | 15 | 3
Sheet4
Name | Rate | Date | Code | ROW_SEQ
Sub Total | 31 | 10/01/2015 | 15 |
Grand Total | 41 | 10/01/2015 | 15 |
但我需要的結果:
Sheet1
Name | Rate | Date | Code | ROW_SEQ
A | 12 | 01/01/2015 | 12 | 1
B | 13 | 01/01/2015 | 12 | 2
Sub Total | 25 | 01/01/2015 | 12 |
C | 10 | 01/01/2015 | 12 | 3
Grand Total | 35 | 01/01/2015 | 12 |
Sheet2
Name | Rate | Date | Code | ROW_SEQ
D | 15 | 10/01/2015 | 15 | 1
E | 16 | 10/01/2015 | 15 | 2
Sub Total | 31 | 10/01/2015 | 15 |
F | 10 | 10/01/2015 | 15 | 3
Grand Total | 41 | 10/01/2015 | 15 |
感謝提前。 :)
使用,你應該只得到兩組。您確定小計和總計對日期或代碼沒有不同的值嗎?也許時間部分的日期是不同的? – juharr
@juhar我確定小計總計和總計沒有不同的值。 – nettoon493
它可能是不同的類型?也許子行和總行的字符串值不是'DateTime'和'int',反之亦然。 – juharr