2

The XLConnect library in R allows reading and writing to Microsoft Excel XLSX spreadsheet files.

However, when using writeWorksheet() or writeWorksheetToFile(), it automatically wraps the text in all cells. How do I turn off the text wrapping? Ideally, I'm looking for generating XLSX spreadsheets with no wrapped text and the optimal width for each column.

Thanks!

enricoferrero
  • 2,249
  • 1
  • 23
  • 28

2 Answers2

0

Here is a function based on XLConnect that saves an .xlsx file to disk without text wrapping. At the end, one of the style choices is to autosize. I suspect there are other choices, which explicitly or implicitly stop text wrapping.

save.xls <- function(df, filename, sheetname="Sheet", create=TRUE, rownames=NULL, startRow=1, zebra=F) {
  require(XLConnect)
  require(stringr)

  if (is.matrix(df)) df <- as.data.frame(df)

  if (!str_detect(filename, "\\.xlsx$")) filename <- str_c(filename, ".xlsx")

  wb <- loadWorkbook(filename, create=create)

  if (existsSheet(wb, sheetname))
    warning(sprintf("Sheet %s already existed and was overwritten", sheetname))

  createSheet(wb, name=sheetname)
  if (!is.null(rownames)) df <- transform(df, rownames = row.names(df))
  writeWorksheet(wb, df, startRow=startRow, sheet=sheetname, rownames=rownames)

  if (zebra) {
    color <- createCellStyle(wb)
    setFillForegroundColor(color, color = XLC$"COLOR.LIGHT_CORNFLOWER_BLUE")
    setFillPattern(color, fill = XLC$FILL.SOLID_FOREGROUND)

    for (i in 1:ncol(df)) {
      setCellStyle(wb, sheet = sheetname, row = seq(startRow+1, nrow(df)+2, 2), col = i, 
                   cellstyle = color)
    }

    #prcntg <- createCellStyle(wb)  see my script of XLConnect.R for how it worked
    #dollar <- createCellStyle(wb)
    #setDataFormat(prcntg, format = "0.0")
    #setDataFormat(dollar, format = "$ 0.00")

    border <- createCellStyle(wb)
    setBorder(border, side = c("bottom","top"), type = XLC$"BORDER.THICK", color = XLC$"COLOR.RED")
    setCellStyle(wb, sheet = "Sheet", row = startRow, col = 1:ncol(df), cellstyle = border)
    setColumnWidth(wb, sheet = "Sheet", column = 1:ncol(df), width = -1) # this autosizes each column
  }

  saveWorkbook(wb)
}
lawyeR
  • 7,488
  • 5
  • 33
  • 63
0

Solved this by switching to the xlsx package, which also has better syntax.

enricoferrero
  • 2,249
  • 1
  • 23
  • 28