Search code examples
c#excelxlsxclosedxml

Set table style. C# - closed xml


I am looking for a way to apply a table style to the inserted data in an excel file. I use the library closed xml How can I do it?

Sample table I want to get

enter image description here

        using (XLWorkbook wb = new XLWorkbook(excel))
        {   IXLWorksheet ws = wb.Worksheets.Last();
            string Qry;
            using (SqlCommand cmd = new SqlCommand(Qry, sqlConn))
            {
                sqlConn.Open();
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    System.Data.DataTable schemaTable = dr.GetSchemaTable();
                    int i = 1;
                    foreach (DataRow rowt in schemaTable.Rows)
                    {
                    while (dr.Read())
                    {
                        row++;
                        for (int j = 0; j < dr.FieldCount; j++)
                        {
                            if (!dr.IsDBNull(j))
                            {
                                switch (dr.GetDataTypeName(j))
                                {
                                    case "Varchar2":
                                        string s = dr.GetString(j);
                                        if (s.Substring(0, 1) == "=")
                                            s = " " + s;
                                        ws.Cell(row, j + 1).Value = s;
                                        break;
                                    case "nvarchar":
                                        ws.Cell(row, j + 1).Value = dr.GetString(j);
                                        break;
                                    default:
                                        break;
                                }}}}}}}

Solution

  • Based on the ClosedXML documentation:

    // create the Excel workbook
    var wb = new XLWorkbook(); 
    
    // creates the worksheet
    var ws = wb.AddWorksheet("Sheet1"); 
    
    // the range for which you want to add a table style
    var range = ws.Range(1, 1, 5, 5); 
    
    // create the actual table
    var table = range.CreateTable();
    
    // apply style
    namesTable.Theme = XLTableTheme.TableStyleLight12;