Search code examples
javascriptarrayscopy-pasterichtext

Copying text that can be pasted as a table in word, excel, etc


I'm not sure if this is considered converting the text data to rich text or not, but I want to take a series of inputs, either from a table or a series of divs (the latter is what I'm using), and place it into a format that can be easily pasted into Word, Outlook or Excel as a table.

I haven't figured out how I'm going to cycle through the list to get all possible entries just yet, but in pseudo code, the following is what I'm looking to do:

var currentLine;    // This is the current line used in the following loop:
for (<each list item found>) {
    currentLine = `${box1A} ${box1B}`;
    <append currentLine to a new line in a textarea element>;
}
<select the text in the textarea element>;
document.execCommand('copy');

Ultimately, the javascript that I will actually use will result in new lines being pasted into a new row (this is good), however, the two strings will be in the came cell. See the following example:

+------------+-------+
| box1A box1B|       |
+------------+-------+
| box2A box2B|       |
+------------+-------+
| box3A box3B|       |
+------------+-------+
| etc.. etc..|       |
+------------+-------+

How can I ensure that box1A will end up being in one cell, and box1B will automatically be pasted into a second cell on the same row? See the following example of what I want:

+-------+-------+
| box1A | box1B |
+-------+-------+
| box2A | box2B |
+-------+-------+
| box3A | box3B |
+-------+-------+
| etc.. | etc.. |
+-------+-------+

Solution

  • From my findings so far, values are separated by tabs. In the example I provided, in order for boxA and boxB to align to different cells on the same row, you can use the following setup for the string:

    var row = `${box1A}\t${box1B}\n${box2A}\t${box2B}\n${box3A}\t${box3B}`
    

    The end result of the above line would yield, once copied onto the clipboard & pasted into Excel:

    +-------+-------+
    | box1A | box1B |
    +-------+-------+
    | box2A | box2B |
    +-------+-------+
    | box3A | box3B |
    +-------+-------+
    

    The \t denotes a Horizontal Tabulator, and will result in automatically entering the next value into the next cell.

    The \n denotes a New Line, and will result in automatically entering the next value into the next cell.