问题描述
我想使用R返回或下载excel,以便在管道工中进行后期响应
我正在读取数据帧并写入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无法打开,因为文件格式或扩展名无效
您能帮我在生成Excel工作表时哪里出错了吗?
解决方法
使用下一版本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,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,n=file.info(filename)$size)
#Return the binary contents
bin
}