R水管工越来越出色xlsx

问题描述

我想使用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
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...