我正在编写一个读取CSV文件并生成两个XLSX文件的代码,具体取决于站点是否需要更新以及位置。例如,我将具有以下示例数据:
我现在遇到的问题是,我想应用Excel表格样式“橄榄绿色,表格样式中18”。我有一个必须通过工作簿的选项,但是由于我不是直接创建工作簿而是要读取CSV文件,我将如何继续呢?
现在,我只是使用val = [('Table1',),('Table2',),('Table3',)]
table_list = [x[0] for x in val]
table_string = ', '.join([x[0] for x in val])
将数据导出到Excel,但是我想对表格应用格式。
示例代码:
write.xlsx()
Update1:添加了示例代码,以显示我使用了1个CSV文件,该文件分为两个excel文件。
更新的代码:
#Determine the input and output parameters
input_file <- choose.files()
output_eu <- "eu.xlsx"
output_noteu <- "noteu.xlsx"
#list of EU countries
eu <- c("Andorra","Austria","Belarus","Belgium","Bosnia and Herzegovina","Bulgaria","Croatia","Czech Republic","Denmark","Estonia","Finland","France","Germany","Greece","Hungary","Iceland","Ireland","Italy","Latvia","Liechtenstein","Lithuania","Luxembourg","Malta","Moldova","Monaco","Montenegro","Netherlands","Norway","Poland","Portugal","Romania","Russia","San Marino","Serbia","Slovakia","Slovenia","Spain","Sweden","Switzerland","Ukraine","United Kingdom")
#reading the csv table
d <- read.table(input_file, sep = ";", header = TRUE, check.names = FALSE)
# get all cases where there is some text in the Update field
updates <- d[d$Update != "", ]
#within updates are there countries in EU
i <- updates$Country %in% eu
eu_up <- updates[i,]
noteu_up <- updates[!i,]
#Creating the excel files
library(openxlsx)
write.xlsx(eu_up, output_eu)
write.xlsx(noteu_up, output_noteu)
答案 0 :(得分:1)
library(openxlsx)
为此很好。
library(openxlsx)
首先,您需要创建一个工作簿:
wb <- createWorkbook()
然后向其中添加两个工作表:
addWorksheet(wb, "EU")
addWorksheet(wb, "NOTEU")
然后让我们写两个表:
writeDataTable(wb, 1, eu_up, startRow = 1, startCol = 1, tableStyle = "TableStyleMedium18")
writeDataTable(wb, 2, noteu_up, startRow = 1, startCol = 1, tableStyle = "TableStyleMedium18")
saveWorkbook(wb, "Tables_with_Formatting.xlsx", overwrite = TRUE)