R - Export excel with formatting table in shiny

2019-08-03 12:29发布

问题:

This is a part of my code.

library(shiny)
library(DT)
library(xlsx)

#r input
df <- data.frame(sd = c("A1", "A1", "A1", "A1", "A1", "A1", "A1"),
                 rsm = c("B", "B", "B", "B", "C", "C", "C"),
                 asm = c("D", "D", "E", "E", "F", "G", "H"),
                 sr = c("I", "J", "K", "L", "M", "N", "O"),
                 revenue _target = c(100, 300, 200, 300, 120, 160, 100),
                 revenue_achive = c(80, 30, 150, 450, 20, 80, 12),
                 revenue_perachive = c(80, 10, 75, 150, 25, 50, 12),
                 quantites_target = c(30, 40, 60, 20, 15, 42, 30),
                 quantities_achive = c(15, 25, 30, 42, 10, 10, 12),
                 quantities_perachive = c(50, 62.5, 50, 210, 66.67, 23.81, 40),
                 day = c(10, 10, 10, 12, 12, 12, 12),
                 month = c(2017, 2017, 2017, 2017, 2017, 2017, 2017),
                 stringsAsFactors = FALSE)
)

 #r formatting table
  sketch <-  htmltools::withTags(table(
  class = 'display',
  thead(
    tr(
      th(rowspan = 2, ''),
      th(rowspan = 2, 'sd'),
      th(rowspan = 2, 'rsm'),
      th(rowspan = 2, 'asm'),
      th(rowspan = 2, 'sr'),
      th(colspan = 2, 'Revenue'),
      th(colspan = 2, 'Quantites'),
      th(rowspan = 2, 'day'),
      th(rowspan = 2, 'month')
    ),
    tr(
      lapply(rep(c('target', 'achive', 'perachive'), 2), th)
    )
  )
))

out_table <- reactive({
out <- df
out
})

output$out_tbl <- DT::renderDataTable (
{out_table()},
rownames = FALSE,
container = sketch
)

fluiRow(
column(
width = 12,
dataTableOutput("out_tbl")
))

After reactiving, in DT::renderDataTable, I add a option: container = sketch. I have 2 misunderstanding:

The first, in htmltools::withTags, I do it if the number of columns merged cell is the same. You see the sample, it is 3 column: "target", "achive" and "perachive". The column named "month" and "year" that I can't merge.

The second, when I download excel, the formatting table is lost. I don't understand.

This is my output picture.

output_picture

How can I do that, like this the output picture?