install.packages(c(“shiny”, “dplyr”,“openxlsx”))
library(shiny) library(dplyr) library(openxlsx) # 定義 UI ui <- fluidPage( titlePanel(“簡單記帳”),
sidebarLayout( sidebarPanel( dateInput(“date”, “日期”, Sys.Date()), textInput(“item”, “項目名稱”), numericInput(“amount”, “金額”, value = 0), selectInput(“type”, “類型”, choices = c(“收入”, “支出”)), actionButton(“addEntry”, “新增記錄”), downloadButton(“downloadData”, “儲存記錄”) ),
mainPanel(
tableOutput("table"),
textOutput("summary")
)
) )
server <- function(input, output, session) { # 儲存記帳數據的 reactiveValues data <- reactiveValues(entries = data.frame(Date = character(), Item = character(), Amount = numeric(), Type = character(), Net = numeric()), netAmount = 0) # 新增記錄的事件 observeEvent(input\(addEntry, { entry <- data.frame(Date = as.character(input\)date), Item = input\(item, Amount = input\)amount, Type = input$type)
# 計算淨額
entry$Net <- ifelse(entry$Type == "收入", entry$Amount, -entry$Amount)
data$entries <- rbind(data$entries, entry)
# 計算總淨額
data$netAmount <- sum(data$entries$Net)
# 清空輸入框
updateDateInput(session, "date", value = Sys.Date())
updateTextInput(session, "item", value = "")
updateNumericInput(session, "amount", value = 0)
updateSelectInput(session, "type", selected = "收入")
})
# 生成數據表格 output\(table <- renderTable({ data\)entries })
# 顯示總淨額 output\(summary <- renderText({ paste("總淨額:", data\)netAmount, “元”) })
# 儲存記錄的事件 output\(downloadData <- downloadHandler( filename = function() { paste("記帳數據_", Sys.Date(), ".xlsx", sep = "") }, content = function(file) { write.xlsx(data\)entries, file, row.names = FALSE) } ) }
shinyApp(ui, server)