I want to get a new line in my excel result such as i would get by going into the cell and pressing Alt+Enter
df <- data.frame(a="Funny\\nNot",b="rofl\nlol",c="hihi\rh3h3")
xlsx::write.xlsx(df,file = "df.xlsx")
To add spacing between lines or paragraphs of text in a cell, use a keyboard shortcut to add a new line. Click the location where you want to break the line. Press ALT+ENTER to insert the line break.
Double click on the cell where you want to insert the line break (or press F2 key to get into the edit mode). Place the cursor where you want to insert the line break. Hold the ALT key and press the Enter key for Windows (for Mac – hold the Control and Option keys and hit the Enter key).
Using the package xlsx
:
Remove the escape '\'
from column a
:
df <- data.frame(a="Funny\nNot",b="rofl\nlol",c="hihi\rh3h3")
library(xlsx)
Create workbook and sheet objects:
wb <- createWorkbook()
sheet <- createSheet(wb, sheetName="sheet1")
Add dataframe:
addDataFrame(df, sheet)
get row 2, column B from the wb/sheet:
rows <- getRows(sheet, rowIndex = 2)
cell_b_2 <- getCells(rows, colIndex = 2)[[1]]
Create a CellStyle
that sets Wrap Text
in Excel:
cs <- CellStyle(wb, alignment = Alignment(wrapText = TRUE))
Apply it to the cell:
setCellStyle(cell_b_2, cs)
Save the workbook:
saveWorkbook(wb, 'df.xlsx')
The resulting workbook looks like this:
Thanks to @lukeA for name dropping.
When I use wrap text
for cells containing "\n"
. I get the desired outcome.
Here is the code I used:
wb <- xlsx::loadWorkbook("df.xlsx")
sheets <- xlsx::getSheets(wb)
sheet <- sheets[[1]] # get specific sheet
rows <- xlsx::getRows(sheet) # get rows
cells <- xlsx::getCells(rows) # get cells
values <- lapply(cells, xlsx::getCellValue) # extract the cell values
wrapStyle <- xlsx::CellStyle(wb) + xlsx::Alignment(horizontal=NULL, vertical=NULL, wrapText=T,
rotation=0, indent=0)
lapply(names(cells),function(c)if(values[[c]] %>% grepl("\\n",.))xlsx::setCellStyle(cells[[c]],wrapStyle))
xlsx::saveWorkbook(wb,"dfWrap.xlsx")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With