Search code examples
sql-serverexcelnewlinecarriage-return

SQL output to Excel Errors


How do I copy hundreds of lines of output from SQL query into individual lines in excel. To clarify each of my hundreds of lines have multiple new line breaks but I don't see those breaks when i do a select.

This is what the data looks like:

Description column in the table:

Hello world this is sample text
another line of text for example
and a third line example

however the data is really like this

Hello world <new line break> this is sample <new line break> text
another line of <new line break>  text for example
and a third <new line break> line example

when i try to copy this into excel i would like it to go into Column H (in my case) each of the lines should be in its own row.

row 1:     Hello world <new line break> this is sample <new line break> text
row 2:     another line of <new line break>  text for example
row 3:     and a third <new line break> line example

but because of the carriage returns this is what i'm getting

row 1:     Hello world
row 2:     this is sample 
row 3:     text
row 4:     another line of
row 5:     text for example
row 6:     and a third
row 7:     line example

if this was a singular column i would make this work, but as i mentioned this is column H I've got a bunch of columns before and after it that need to line up.


Solution

  • In your SQL query, instead of replacing the line feeds within a field with spaces, replace them with:

       " & CHAR(10) & "
    

    Have that column start with an equals sign and double quote, and end with double quote. So, test data would output as

    ="Hello world" & CHAR(10) & "this is sample " & CHAR(10) & " text"
    ="another line of " & CHAR(10) & "  text for example"
    ="and a third " & CHAR(10) & " line example"
    

    Put this into Excel. This will look like a mess, until you make sure that under Format Cells you've checked 'Wrap Text', then the carriage returns will appear within the cells.