How to add line breaks in Google Sheets using the API?

I’m trying to figure out how to insert line breaks in a cell when using the Google Sheets API. I want the cell to show this:

First Line
Second Line

What should I include in the setValue() method to achieve that? Here’s my current attempt:

function updateCell(cell){
  cell.setValue('First Line
                  Second Line')
}

Unfortunately, this isn’t working for me. I’ve also tried copying the value from another cell that has the right formatting:

cell.setValue(anotherCell.getValue());

This works if the other cell has the line breaks I want, but I’m not sure how to check what’s inside that cell. How can I correctly use line breaks in cell values with the API?

The escape sequence approach mentioned above is correct, but there’s an important detail about text wrapping that can trip you up. When you use \n for line breaks, you also need to ensure the cell’s wrap strategy is properly configured through the API. You can do this by using the batchUpdate method with a repeatCell request that sets the wrapStrategy to WRAP. Without this formatting change, the line break characters will be there but won’t display as separate lines in the sheet. I ran into this exact issue when building a reporting tool last year and spent way too much time debugging before realizing the formatting wasn’t being applied automatically.

Another thing to watch out for is character encoding issues when working with line breaks through the API. I’ve encountered situations where the \n characters get interpreted differently depending on how you’re sending the data to the API. If you’re working with batched requests or sending data from different sources, make sure you’re consistently using the same line break format. Also worth noting that if you’re reading values back from cells that contain line breaks, you’ll see the actual \n characters in the returned string, which can be useful for debugging. When I was working on a project that involved importing multi-line descriptions, I had to be careful about preserving these characters when processing the data further downstream.

you can use \n in your string like cell.setValue('First Line\nSecond Line') for line breaks. just remeber to set the cell to wrap text, or it won’t show right.