rexcelopenxls

R - Adding a total row in Excel output


I want to add a total row (as in the Excel tables) while writing my data.frame in a worksheet. Here is my present code (using openxlsx):

writeDataTable(wb=WB, sheet="Data", x=X, withFilter=F, bandedRows=F, firstColumn=T)

X contains a data.frame with 8 character variables and 1 numeric variable. Therefore the total row should only contain total for the numeric row (it will be best if somehow I could add the Excel total row feature, like I did with firstColumn while writing the table to the workbook object rather than to manually add a total row).

I searched for a solution both in StackOverflow and the official openxslx documentation but to no avail. Please suggest solutions using openxlsx.

EDIT:

Adding data sample:

A  B  C  D  E  F  G  H  I
a  b  s  r  t  i  s  5  j
f  d  t  y  d  r  s  9  s
w  s  y  s  u  c  k  8  f

After Total row:

    A  B  C  D  E  F  G  H  I
    a  b  s  r  t  i  s  5  j
    f  d  t  y  d  r  s  9  s
    w  s  y  s  u  c  k  8  f
    na na na na na na na 22 na

Solution

  • library(janitor)
    adorn_totals(df, "row")
    
    #>      A B C D E F G  H I
    #>      a b s r t i s  5 j
    #>      f d t y d r s  9 s
    #>      w s y s u c k  8 f
    #>  Total - - - - - - 22 -
    

    If you prefer empty space instead of - in the character columns you can specify fill = "" or fill = NA.