如何将 html 表与图像 src 一起下载为 csv [英] How to download html table as csv along with images src

查看:19
本文介绍了如何将 html 表与图像 src 一起下载为 csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张表,我想将它导出为 csv,但该表也有图像.我知道 csv 不支持图像,但我想获取图像的 src 而不是图像文件.

I have a table and i want to export it as csv but the table also has images. I know csv does not support images, but i want to get the src of the image and not the image file.

示例表

<table>
    <tbody>
      <tr>
        <td>John Doe</td>
        <td>Student</td>
        <td><img src="xyz.com/image.png"></td>
      </tr>
      <tr>
        <td>Jane Doe</td>
        <td>Teacher</td>
        <td><img src="abc.com/image.png"></td>
      </tr>
    </tbody>
 </table>

推荐答案

适用于将来在没有 Excel 的情况下阅读本文并希望将数据格式化为 CSV 的任何人.这是如何做到的:

For anyone who reads this in the future without having Excel and who wants to get the data formatted as CSV. This is how to do that:

let rows = document.getElementsByTagName('tr');

let cells;
let csv = "";

let csvSeparator = ";"; // Sets the separator between fields
let quoteField = true; // Adds quotes around fields

let regex = /.*<img.*src="(.*?)"/i

for (let row = 0; row < rows.length; row++) {
  cells = rows[row].getElementsByTagName('td');
  if (cells.length === 0) {
    cells = rows[row].getElementsByTagName('th');
  }
  for (let cell = 0; cell < cells.length; cell++) {
    if (quoteField) { csv += '"'; }
    
    if (regex.test(cells[cell].innerHTML)) {
      csv += cells[cell].innerHTML.match(regex)[1];
    } else {
      csv += cells[cell].innerText;
    }
    
    if (quoteField) { csv += '"'; }
    
    if (cell === cells.length - 1) {
      csv += "\n";
    } else {
      csv += csvSeparator;
    }
  }
}

function downloadToFile(content, filename, contentType) {
  const a = document.createElement('a');
  const file = new Blob([content], {type: contentType});
  
  a.href = URL.createObjectURL(file);
  a.download = filename;
  
  // To generate a link, use this:
  a.innerHTML = "Download CSV";
  document.body.appendChild(a);

  // If you want to automatically download then use this instead:
  /*
  a.click();
    URL.revokeObjectURL(a.href);
  */
}

console.log(csv);

downloadToFile(csv, 'csv-export.csv', 'text/plain');

* {
  font-family: sans-serif;
}

table {
  border-collapse: collapse;
}

table, th, td {
  border: 1px solid #ccc;
  padding: 5px 10px;
}

a {
  text-decoration: none;
}

<table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Occupation</th>
        <th>Photo</th>
      </tr>
    </thead>
    <tbody> 
      <tr>
        <td>John Doe</td>
        <td>Student</td>
        <td><img src="xyz.com/image.png"></td>
     </tr>
     <tr>
        <td>Jane Doe</td>
        <td>Teacher</td>
        <td><img src="abc.com/image.png"></td>
     </tr>
    </tbody>
 </table>

这篇关于如何将 html 表与图像 src 一起下载为 csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆