R 管道工得到 excel (xlsx)

R plumber getting as excel (xlsx)

我想 return 或下载 excel 用于 post 水管工响应

我正在读取数据框并写入 xlsx:

文件名:sample.R

xlsx_df = read.xlsx(file="My_File.xlsx", sheetName="Overview", header=T, stringsAsFactors=F, encoding="UTF-8")
write.xlsx(xlsx_df, file="Output_File.xlsx", sheetName="Sample_Sheet", row.names=F, showNA=F)
#* @serializer contentType list(type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
#* @get/excel
function(req, res){
  filename <- file.path(tempdir(), "Output_File.xlsx")
  write.xlsx2(iris, filename, row.names = FALSE)
  include_file(filename, res, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
} 

文件名:Plumber.R

r <- plumb("sample.R")
r$run(port=8011)

当我查看响应正文时,我得到了一些奇怪的响应,这些响应不可读。 如果我尝试打开 excel,我会收到错误 excel cannot open because file format or extension is invalid

你能帮我看看我在生成 excel sheet 时哪里出错了吗?

使用下一版本 1.0.0

library(xlsx)
library(plumber)

#* @get /excel
function(req, res){
  filename <- file.path(tempdir(), "Output_File.xlsx")
  on.exit(unlink(filename))
  write.xlsx2(iris, filename, row.names = FALSE)
  as_attachment(readBin(filename, "raw", file.info(filename)$size), basename(filename))
}

这对我有用,希望对某人有所帮助。

library(plumber)
library(xlsx)

#* @serializer contentType list(type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
#* @get /report/
api_get_report <-function(req, res){
  
  df <- data.frame(CHAR = letters, NUM = rnorm(length(letters)), stringsAsFactors = F)
  filename <- file.path(tempdir(), "alphabet.xlsx")
  write.xlsx(df, filename, sheetName="Alphabets", append=TRUE)
  attachmentString = paste0("attachment; filename=Output_File.xlsx", filename)
  
  res$setHeader("Content-Disposition", attachmentString)
  
  # Read in the raw contents of the binary file
  bin <- readBin(filename, "raw", n=file.info(filename)$size)
  
  #Return the binary contents
  bin
}