openxlsx format cells as number with comma and decimal places

Jason picture Jason · Apr 12, 2018 · Viewed 7.5k times · Source

How can one create an excel file using openxlsx where the number formatting includes both comma thousand separators and 2 decimal places? I have tried the code below, but no luck on the formatting.

# 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)

Answer

Felipe Alvarenga picture Felipe Alvarenga · Apr 12, 2018

You can set the default formatting for the 2 decimal cases prior to adding the thousands format.

    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

This will ensure that the thousands formatting happens on a value that already has only 2 decimal cases.