gpt4 book ai didi

r - 如何将数据从 Shiny 下载到多张纸上?

转载 作者:行者123 更新时间:2023-12-04 02:41:45 24 4
gpt4 key购买 nike

我们如何将 Shiny 中的数据下载到多个工作表中并命名每个工作表?

例如下图,ginberg将mtcars数据保存在sheet1中,我们可以将 head(mtcars) 保存在 sheet2 中吗?此外,我们能否以不同的方式命名这些工作表,例如 sheet_data、sheet_head

引用:https://community.rstudio.com/t/r-shiny-to-download-xlsx-file/18441/3来自 https://community.rstudio.com/u/ginberg 的代码

library(writexl)
ui <- fluidPage(
downloadButton("dl", "Download")
)
server <- function(input, output) {
data <- mtcars

output$dl <- downloadHandler(
filename = function() { "ae.xlsx"},
content = function(file) {write_xlsx(data, path = file)}
)

### Trial 1
# output$dl <- downloadHandler(
# filename = function() { "ae.xlsx"},
# content = function(file) {
# fname <- paste(file,"xlsx",sep=".")
# wb <- loadWorkbook(fname, create = T)#createWorkbook()
# createSheet(wb, name = "data")
# writeWorksheet(wb, head(mtcars), sheet = "sheet_head")
# saveWorkbook(wb)
# file.rename(fname, file)}

# Trial 2
# filename = function() {"both_data.xlsx"},
# content = function(file) {
# write_xlsx(mtcars, file="sheet_data.xlsx")
# write_xlsx(head(mtcars), file="sheet_head.xlsx")
#
# channel <- odbcConnectExcel(xls.file = file,readOnly=FALSE)
# sqlSave(channel, mtcars, tablename = "sheet_data")
# sqlSave(channel, head(mtcars), tablename = "sheet_head")
# odbcClose(channel)

)
}
shinyApp(ui, server)

最佳答案

是的,您可以命名工作表并在不同的工作表上包含不同的数据框。

使用write_xlsx,您可以提供数据帧的命名列表

例如:

server <- function(input, output) {

data_list <- reactive({
list(
sheet_data = mtcars,
sheet_head = head(mtcars)
)
})

output$dl <- downloadHandler(
filename = function() {"ae.xlsx"},
content = function(file) {write_xlsx(data_list(), path = file)}
)
}

list 是在 reactive 函数中创建的,您可能希望根据用户交互更改包含的数据。

关于r - 如何将数据从 Shiny 下载到多张纸上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59071409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com