首页 > 代码库 > C#DataTable导出Excel

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