The front end copies the string to excel to generate a table

Scenario requirements: There is a button on the front-end page. When clicked, a piece of text will be copied, and then the copied text will be directly copied and pasted into the excel table, and the corresponding table data will be automatically formed.
insert image description here

The following code can be copied and used directly (effective likes support a wave):

    copyAll () {
    
    
      let tableArr = [
        {
    
     name: '张三', certno: '220381197902121201' },
        {
    
     name: '李四', certno: '220381197902121202' },
        {
    
     name: '王五', certno: '220381197902121203' },
        {
    
     name: '赵六', certno: '22038119790212123X' },
      ]//列表数据

      let strAll = `姓名\t证件号码\n`   // \t 相当于tab键 \n 是换行符  这里写上表头
      tableArr.forEach(ele => {
    
    
        //注意这里为什么多加个字符 '  是因为当该项是数字时候,若数字太长 在excel里是显示成E+展示不全  前面加上'后改想就变成字符串格式了 就会完全展示开
        let str1 = `${
    
    ele.name}\t'${
    
    ele.certno}\n` //注意使用模板字符串`` 可以识别转移字符串tab键\t和换行符\n

        // let str1 = `${ele.name}\t${ele.certno}\n`
        // let str1 = `${ele.name}\t${123}\n`
        strAll = strAll + str1 // 将其拼装成一个有格式的字符串即可
      })

      // 以下是复制逻辑
      let oInput = document.createElement('textarea') //textarea会复制保留格式
      oInput.value = strAll
      document.body.appendChild(oInput)
      oInput.select() // 选择对象;
      document.execCommand('Copy') // 执行浏览器复制命令
      this.$message({
    
    
        message: '信息已复制到剪切板!',
        type: 'success'
      })
      oInput.remove()
    },

Logic: The front end splices the table data into a string, and this string contains the tab line break key \t and line break \n in the corresponding position .

1. At the beginning, I wrote \t and \n directly in the string, and the copied text contains \t and \n, but this is not acceptable, and excel will directly understand these escape characters as strings for display come out
insert image description here

2. Later, write \t and \n into the template string ``, the template string will retain the format, and the table can be generated after copying to excel.
insert image description here

3. When the item is in numeric format and is too long, it will not be displayed completely, but the string format can be displayed in full. As for how to set it as a text format, I happened to click to click the number format into a string, and found that there was an extra character ' in front of it, so I added ' to get a string.insert image description here insert image description here

4. For the third point, you can also not add ', but before you need to paste the excel sheet, you need to set the entire excel sheet to text format.
insert image description here

Guess you like

Origin blog.csdn.net/i_am_a_div/article/details/128371971