Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openxlsx format cells as number with comma and decimal places

Tags:

r

openxlsx

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)
like image 724
Jason Avatar asked Apr 12 '18 15:04

Jason


1 Answers

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.

like image 62
Felipe Alvarenga Avatar answered Sep 19 '22 11:09

Felipe Alvarenga