gpt4 book ai didi

r - 如何在 Shiny 上通过 downloadHandler 下载工作簿?

转载 作者:行者123 更新时间:2023-12-03 21:16:53 25 4
gpt4 key购买 nike

我们如何将工作簿保存在某个文件夹中
并使其可供用户下载?

引用:
Shiny + downloadHandler + Openxlsx does not generate a xlsx file

程序:

  • 创建数据
  • 另存为工作簿
  • 使其可通过以下方式下载
    将其读取为 xlsx 文件

  • 即使工作簿被写入文件夹,
    下载该工作簿时出错。
    library(shiny)
    library(openxlsx)
    library(writexl)
    library(tidyverse)
    ui <- fluidPage(
    downloadButton("dl", "Download")
    )

    server <- function(input, output) {
    data1 = mtcars[,c(1,2)] %>% head() # data for Col 1 ,until Row 6
    data2 = gapminder::gapminder[,c(1,4)] %>% head() # data for Col 1 , Row from 8 until Row 13
    data3 = mtcars[,c(1,2)] %>% tail() # data for Col 1 , Row from 15 until Row 20

    # Creating a workbook for user to download
    wb <- createWorkbook()
    addWorksheet(wb, sheetName = "sheet1")
    writeData(wb, sheet = 1, x = data1, startCol = 1, startRow = 1)
    writeData(wb, sheet = 1, x = data2, startCol = 1, startRow = 8)
    writeData(wb, sheet = 1, x = data3, startCol = 1, startRow = 15)
    ex_wb <- paste0("example", ".xlsx")
    saveWorkbook(wb, file = ex_wb, overwrite = TRUE)

    output$dl <- downloadHandler(
    filename = function(){ex_wb # filename
    },
    content = function(file) {
    # Content to be available for user to download
    read.xlsx(ex_wb) # Making dataframe available for user to download
    })
    }
    shinyApp(ui, server)

    最佳答案

    试试这个:

    library(shiny)
    library(openxlsx)
    library(writexl)
    library(tidyverse)
    ui <- fluidPage(
    downloadButton("dl", "Download")
    )

    server <- function(input, output) {
    data1 <- mtcars[, c(1, 2)] %>% head() # data for Col 1 ,until Row 6
    data2 <- gapminder::gapminder[, c(1, 4)] %>% head() # data for Col 1 , Row from 8 until Row 13
    data3 <- mtcars[, c(1, 2)] %>% tail() # data for Col 1 , Row from 15 until Row 20

    # Creating a workbook for user to download
    wb <- createWorkbook()
    addWorksheet(wb, sheetName = "sheet1")
    writeData(wb, sheet = 1, x = data1, startCol = 1, startRow = 1)
    writeData(wb, sheet = 1, x = data2, startCol = 1, startRow = 8)
    writeData(wb, sheet = 1, x = data3, startCol = 1, startRow = 15)


    output$dl <- downloadHandler(
    filename = function() {
    paste0("example", ".xlsx")
    },
    content = function(file) {
    saveWorkbook(wb, file = file, overwrite = TRUE)
    }
    )
    }
    shinyApp(ui, server)

    关于r - 如何在 Shiny 上通过 downloadHandler 下载工作簿?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59718424/

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