【发布时间】:2021-11-09 10:20:41
【问题描述】:
我创建了以下应用程序来从 R 中的 temp 文件夹中读取 excel 文件。我想在 R 中保留文件格式闪亮
library(XLConnect)
library(shiny)
library(openxlsx)
library(readxl)
ui <- fluidPage(
titlePanel("Writer App"),
sidebarLayout(sidebarPanel(fileInput(inputId = "file", label = "Read File Here", accept = c(".xlsx")), downloadLink("downloadData", "Download")), mainPanel(dataTableOutput(outputId = "table1"))))
server <- function(input, output) {
datasetInput <- reactive({
infile<- input$file
if (is.null(infile))
return(NULL)
#READ .XLSX AND .CSV FILES
if(grepl(infile, pattern = ".xlsx" )==T){data=read_excel(infile$datapath)} else
if(grepl(infile , pattern = ".csv" )==T){data=read.csv(infile$datapath )}
#RENAME DATAFRAME WITH UNDERSCORES
names(data)<-gsub(pattern = " ", replacement = "_", x = names(data))
return(data) })
output$table1 <- renderDataTable({
return(datasetInput())})
output$downloadData <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".xlsx", sep="")},
content = function(file) {
tf<-tempdir()
Files=list.files(path=tf, pattern=".xlsx", recursive = TRUE)[1]
file.copy(from =paste0(tf, "/",Files ), to= "temp_1.xlsx")
wb2 <- loadWorkbook(file = "temp_1.xlsx")
df_1<-data.frame("DF"= c(1:3))
addWorksheet(wb = wb2,sheetName = "Parameters1")
writeData(wb2, "Parameters1", df_1, startCol = 1, startRow = 2, rowNames = TRUE)
saveWorkbook(wb2, file)})
}
shinyApp(ui = ui, server = server)
下载按钮 (output$downloadData) 有一个命令,用于将包含格式的文件从临时位置复制到新文件 temp.xlsx。该文件接下来作为工作簿加载。将新工作表 Parameters1 添加到工作簿 wb2。接下来,将数据框(df_1)写入工作表Parameters1并下载文件。
现在,output$downloadData 中的代码在 R 控制台中工作,但在 R Shiny 的反应式环境中不工作。
loadworkbook 命令似乎有错误。我可以通过 read_excel 获取文件,然后插入数据。然而,这并不保留加载的 Excel 工作表的格式。我请求有人指导我。
【问题讨论】:
-
您正在阅读哪个文件?
Files=list.files(path=tf, pattern=".xlsx", recursive = TRUE)[1]是不是用户上传的同一个excel文件? -
是的。这是同一个文件。但出于数据安全的原因,它被闪亮存储在一个临时文件夹中。 wb2 对象被创建。显然问题在于保存功能。这就是问题所在
标签: r shiny download readxl openxlsx