rshiny1:簡單的接入api實現下載功能

weixin_33866037發表於2017-01-09
#windows下操作:
library("shiny")
library("RCurl")
library("rjson")
library("xlsx")
# Define UI for application that plots random distributions 
ui <- shinyUI(pageWithSidebar(
  
  # Application title
  headerPanel("平臺名字"),
  
  # Sidebar with a slider input for number of observations
  sidebarPanel(
    fileInput('file1', 'Choose xlsx File',
              accept=c('text/csv', 'text/comma-separated-values,text/plain')),
   # helpText('一二三四五'),
    br(),
    downloadButton('downloadDa1ta', 'Download')
  ),
  # Show a plot of the generated distribution
  mainPanel(
    tableOutput('table')
  )
))

server <- shinyServer(function(input, output) {
  dataInput<- reactive({
    inFile <- input$file1
    if (is.null(inFile)){
      return(NULL)
    }
    data_file<-read.xlsx(inFile$datapath,1,encoding = 'UTF-8',header = FALSE)
    #data_file <- unname(unlist(data_file))
    data_file <- as.character(data_file[,1])
    value<-c()
    len=length(data_file)
    for(i in data_file){
      url <- getURL(paste("API網址/text=",URLencode(i),sep=''))#APIget方式與text進行拼接
      result <- fromJSON(url)
      value<- rbind(value,result$result)
    }
    result<- as.data.frame(cbind(data_file,value))
    colnames(result) <- c("text","label")
    result
  })
  
  output$table <- renderTable({
    dataInput()
  })
  output$downloadData <- downloadHandler(
    filename = function() {
      paste('Result', '.xlsx', sep='') 
    },
    content = function(file) {
      write.xlsx(dataInput(), file)
    }
  )
})

shinyApp(ui = ui,server = server)

相關文章