標籤:c# datatable excel
先將資料庫中的資料讀取到DataTable中,然後調用下面的代碼,"cells.Add(1, 1, "表頭1");"這段代碼的意思是在Excel中添加一行表頭,比如“姓名”,“性別”,“聯絡電話”等,需要幾列就對應的添加幾列。“cells.Add(2 + row, 1, dt.Rows[row]["對應表頭1的欄位"]);”這段代碼的意思是擷取對應表頭的資料,比如表頭1如果為“姓名”,這裡"對應表頭1的欄位"就改成欄位"Name"。
DataTable dt = GetDataTable(); if (dt == null) return; try { XlsDocument xls = new XlsDocument(); string fileName = Guid.NewGuid().ToString() + ".xls"; xls.FileName = fileName; string sheetName = "Sheet1"; Worksheet sheet = xls.Workbook.Worksheets.Add(sheetName); Cells cells = sheet.Cells; cells.Add(1, 1, "表頭1"); cells.Add(1, 2, "表頭2"); cells.Add(1, 3, "表頭3"); cells.Add(1, 4, "表頭4"); cells.Add(1, 5, "表頭5"); cells.Add(1, 6, "表頭6"); cells.Add(1, 7, "表頭7"); cells.Add(1, 8, "表頭8"); for (int row = 0; row < dt.Rows.Count; row++) { cells.Add(2 + row, 1, dt.Rows[row]["對應表頭1的欄位"]); cells.Add(2 + row, 2, dt.Rows[row]["對應表頭2的欄位"]); cells.Add(2 + row, 3, dt.Rows[row]["對應表頭3的欄位"]); cells.Add(2 + row, 4, dt.Rows[row]["對應表頭4的欄位"]); cells.Add(2 + row, 5, dt.Rows[row]["對應表頭5的欄位"]); cells.Add(2 + row, 6, dt.Rows[row]["對應表頭6的欄位"]); cells.Add(2 + row, 7, dt.Rows[row]["對應表頭7的欄位"]); cells.Add(2 + row, 8, dt.Rows[row]["對應表頭8的欄位"]); } string filePath = Server.MapPath("~/tmp/"); xls.Save(filePath); xls = null; } catch (Exception) { throw; }
C#DataTable匯出Excel