Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a line break / new line in excel file with r xlsx

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

data + code

df <- data.frame(a="Funny\\nNot",b="rofl\nlol",c="hihi\rh3h3")

xlsx::write.xlsx(df,file = "df.xlsx")
like image 842
Andre Elrico Avatar asked Oct 24 '17 09:10

Andre Elrico


People also ask

What is the code for a line break in Excel?

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.

How do I insert a line break in an Excel cell on a Mac?

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


2 Answers

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:

excel-output

like image 77
clemens Avatar answered Oct 21 '22 01:10

clemens


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")
like image 33
Andre Elrico Avatar answered Oct 21 '22 02:10

Andre Elrico