【问题标题】:How can I add a vertical line to a datatable?如何在数据表中添加垂直线?
【发布时间】:2019-05-15 05:35:48
【问题描述】:

我想在 3 列之间添加一条线:Species Sepal 和 Petal。 我该怎么做?

sketch = htmltools::withTags(table(
  class = 'display',
  thead(
    tr(
      th(rowspan = 2, 'Species'),
      th(colspan = 2, 'Sepal'),
      th(colspan = 2, 'Petal')
    ),
    tr(
      lapply(rep(c('Length', 'Width'), 2), th)
    )
  )
))
print(sketch)
datatable(iris[1:20, c(5, 1:4)], container = sketch, rownames = FALSE)

【问题讨论】:

    标签: r dt


    【解决方案1】:

    你可以的

    datatable(iris[1:20, c(5, 1:4)], container = sketch, rownames = FALSE) %>% 
      formatStyle(c(1,3), `border-right` = "solid 2px")
    

    对于表头的边框,可以在sketch中设置CSS:

    sketch = htmltools::withTags(table(
      class = 'display',
      thead(
        tr(
          th(rowspan = 2, style = "border-right: solid 2px;", 'Species'),
          th(colspan = 2, style = "border-right: solid 2px;", 'Sepal'),
          th(colspan = 2, 'Petal')
        ),
        tr(
          th("Length"),
          th(style = "border-right: solid 2px;", "Width"),
          th("Length"),
          th("Width")
        )
      )
    ))
    

    【讨论】:

      【解决方案2】:

      您可以添加一个 css 类,在单元格的右侧添加一个边框,并使用 columnDefs 选项将其应用于相关列。对于标头,您可以使用 initComplete 回调设置类。

      这是一个例子:

      library(shiny)
      library(DT)
      library(htmltools)
      
      runApp(shinyApp(
        ui <- basicPage(
          tags$head(
            tags$style(HTML(".cell-border-right{border-right: 1px solid #000}"))),
          DT::dataTableOutput('table1')
        ),
        server = function(input, output) {
          output$table1 <- DT::renderDataTable({
            datatable(data.frame(a1 = 1, b1 = 2, a2 = 3, b2 = 4), rownames = FALSE,
                      container = withTags(table(
                        class = 'display',
                        thead(
                          tr(
                            th(colspan = 2, 'g1'),
                            th(colspan = 2, 'g2')
                          ),
                          tr(
                            lapply(rep(c('a', 'b'), 2), th)
                          )
                        )
                      )),options = list(initComplete = JS(
                        "function(settings, json) {",
                        "var headerBorder = [0,1];",
                        "var header = $(this.api().table().header()).find('tr:first > th').filter(function(index) {return $.inArray(index,headerBorder) > -1 ;}).addClass('cell-border-right');",
                        "}"),columnDefs=list(list(className="dt-right cell-border-right",targets=1))
            ))
          })
        }
      ))
      

      jquery选择器用于选择表头的第一行和第一个th标签,这样边框只加到g1单元格上。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-18
        • 2023-03-23
        • 1970-01-01
        • 2021-09-22
        • 1970-01-01
        • 2020-06-06
        • 1970-01-01
        • 2019-05-05
        相关资源
        最近更新 更多