7

如何使用 openxlsx 创建一个 excel 文件,其中数字格式包括逗号千位分隔符和 2 个小数位?我已经尝试了下面的代码,但格式化没有运气。

# Create Customer Dataset
cust <- data.table(Customer = c("Sue", "Ben", "Jason", "Cody"), Sales = 
c(5654.3456, 29384.4, 729, .4093))

# Start Workbook
wb <- createWorkbook()

# Set Sheet Name
sheet = "Customers Report"

# Initiate worksheet within workbook
addWorksheet(wb = wb, sheet = sheet)

# Add Formatting to Spreadsheet
addStyle(wb = wb, sheet = sheet, style = createStyle(numFmt = "NUMBER"), rows = 2:6, cols = 2)
addStyle(wb = wb, sheet = sheet, style = createStyle(numFmt = "COMMA"), rows = 2:6, cols = 2, stack = TRUE)

# Write Customer Dataset to Spreadsheet
writeData(wb = wb, sheet = sheet, x = cust, headerStyle = 
createStyle(textDecoration = "bold"))

# Write Workbook to File
saveWorkbook(wb = wb, file = "~/Desktop/Customer_Report.xlsx", overwrite = TRUE)
4

2 回答 2

11

在添加千位格式之前,您可以设置 2 位小数的默认格式。

    wb      = createWorkbook()
    options("openxlsx.numFmt" = "0.00") # 2 decimal cases formating
    styleT <- createStyle(numFmt = "#,##0.00") # create thousands format
    addStyle(wb, sheetName, styleT,
             rows = 'yourrows',cols = 'yourcols',
             gridExpand = T, stack = T) # add thousands format to designated cols and rows

这将确保千位格式发生在一个已经只有 2 个小数大小写的值上。

于 2018-04-12T15:33:31.653 回答
5

我在写问题时找到了答案,但我想我会继续发布它,以防其他人在路上遇到同样的问题。我通过 github openxlsx issue #75找到了这个答案。请看下面的代码块:

# Add Formatting to Spreadsheet
addStyle(wb = wb, sheet = sheet, style = createStyle(numFmt = "#,##0.00"), rows = 2:6, cols = 2)

我发现当你想要一个数字时使用“0”,无论它是否为 0,并且你使用“#”来表示潜在数字的占位符。例如,如果数字为 .4093,如上所示,则将其格式化为 0.41;如果数字为 29384.4,如上所示,则将其格式化为 29,384.40。

于 2018-04-12T15:42:47.137 回答