First read the data in the database into the DataTable, and then call the following code, "cells." ADD (1, 1, "Table header 1"); " This code means adding a row of headers in Excel, such as "name", "Gender", "Contact phone", and so on, adding several columns to the corresponding columns. "Cells. ADD (2 + row, 1, dt. rows[row]["field corresponding to table Header 1"]); " This code means to obtain the corresponding header data, such as the table header 1 if "name", here "corresponding to the table header 1 field" is changed to the field "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, "table header 1"); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSp; cells. ADD (1, 2, "table Header 2"); cells. ADD (1, 3, "table Header 3"); cells. ADD (1, 4, "table Header 4"); cells. ADD (1, 5, "table Header 5"); cells. ADD (1, 6, "table header 6"); cells. ADD (1, 7, "Table Header 7"); cells. ADD (1, 8, "table header 8"); for (int row = 0; Row < dt. rows.count; row++) { cells. ADD (2 + row, 1, dt. rows[row]["field corresponding to table Header 1"]); cells. ADD (2 + rOw, 2, dt. rows[row]["field corresponding to table Header 2"]); cells. ADD (2 + row, 3, dt. rows[row]["field corresponding to table Header 3"]); cells. ADD (2 + row, 4, dt. rows[row]["field corresponding to table Header 4"]); cells. ADD (2 + row, 5, dt. rows[row]["field corresponding to table Header 5"]); cells. ADD (2 + row, 6, dt. rows[row]["field corresponding to table header 6"]); cells. ADD (2 + row, 7, dt. rows[row]["field corresponding to table Header 7"]); cells. ADD (2 + row, 8, dt. rows[row]["field corresponding to table Header 8"]); } string Filepath = server.mappath ("~/tmp/"); xls. Save (FilePath); xls = null; } catch (Exception) { throw; }
C#datatable exporting Excel