通过jQuery将HTML表格转换为CSV

时间:2015-09-02 10:13:32

标签: javascript jquery html csv

我有一个问题,我试图将html表导出到csv文件。问题是没有下载框,但我知道我的JS功能是通过警报检查运行的。

我想知道它是否可以是我从这样的现有csv文件生成的表:

  echo "<table>\n\n";
  $f = fopen("../translations/EXAMPLE.csv", "r");
  while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td contenteditable>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
  }
  fclose($f);
  echo "\n</table>";

我有一个按钮来调用javascript:

<button class='saveCSV' style='float:right;'>Save</button>

这是javascript文件:

$(document).ready(function () {

    function exportTableToCSV($table, filename) {

        var $rows = $table.find('tr:has(td)'),

            // Temporary delimiter characters unlikely to be typed by keyboard
            // This is to avoid accidentally splitting the actual contents
            tmpColDelim = String.fromCharCode(11), // vertical tab character
            tmpRowDelim = String.fromCharCode(0), // null character

            // actual delimiter characters for CSV format
            colDelim = '","',
            rowDelim = '"\r\n"',

            // Grab text from table into CSV formatted string
            csv = '"' + $rows.map(function (i, row) {
                var $row = $(row),
                    $cols = $row.find('td');

                return $cols.map(function (j, col) {
                    var $col = $(col),
                        text = $col.text();

                    return text.replace(/"/g, '""'); // escape double quotes

                }).get().join(tmpColDelim);

            }).get().join(tmpRowDelim)
                .split(tmpRowDelim).join(rowDelim)
                .split(tmpColDelim).join(colDelim) + '"',

            // Data URI
            csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

        $(this)
            .attr({
            'download': filename,
                'href': csvData,
                'target': '_blank'
        });
                alert("KØRT");
    }

    // This must be a hyperlink
    $(".saveCSV").on('click', function (event) {
        // CSV
        exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);

        // IF CSV, don't do event.preventDefault() or return false
        // We actually need this to be a typical hyperlink
    });
});

任何人都知道这里的错误和csv文件没有导出?

2 个答案:

答案 0 :(得分:0)

您是否尝试删除encodeURIComponent方法?通过一些初步测试,我发现这会打破功能。所以你的代码可能看起来像这样:

var csvData = 'data:application/csv;charset=utf-8,' + csv;

Here's an example这在行动中。

另请注意,由于download属性不受普遍支持,因此您尝试执行的操作无法在每个浏览器中运行。有关支持的更多信息,请参阅here

答案 1 :(得分:0)

只需将csvData转换为blob文件或base64文件,然后使用ajax发送到服务器。记下document.ready之后添加的两个函数。

    $(document).ready(function () {
    function dataURItoBlob(dataURI) {
        // convert base64/URLEncoded data component to raw binary data held in a string
        var byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(dataURI.split(',')[1]);
        else
            byteString = unescape(dataURI.split(',')[1]);

        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

        // write the bytes of the string to a typed array
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        return new Blob([ia], {type:mimeString});
    }

function uploadCSV( blob ) {
  var reader = new FileReader();
  reader.onload = function(event){
    var fd = {};
    fd["fname"] = "example.csv";
    fd["data"] = event.target.result;
    $.ajax({
      type: 'POST',
      url: 'upload.php',
      data: fd,
      dataType: 'text'
    }).done(function(data) {
        console.log(data);
    });
  };
  reader.readAsDataURL(blob);
}
        function exportTableToCSV($table, filename) {

            var $rows = $table.find('tr:has(td)'),

                // Temporary delimiter characters unlikely to be typed by keyboard
                // This is to avoid accidentally splitting the actual contents
                tmpColDelim = String.fromCharCode(11), // vertical tab character
                tmpRowDelim = String.fromCharCode(0), // null character

                // actual delimiter characters for CSV format
                colDelim = '","',
                rowDelim = '"\r\n"',

                // Grab text from table into CSV formatted string
                csv = '"' + $rows.map(function (i, row) {
                    var $row = $(row),
                        $cols = $row.find('td');

                    return $cols.map(function (j, col) {
                        var $col = $(col),
                            text = $col.text();

                        return text.replace(/"/g, '""'); // escape double quotes

                    }).get().join(tmpColDelim);

                }).get().join(tmpRowDelim)
                    .split(tmpRowDelim).join(rowDelim)
                    .split(tmpColDelim).join(colDelim) + '"',

                // Data URI
                csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

            var asblob = dataURItoBlob(csvData);
            uploadCSV( asblob ); //prepare and send via ajax post. The ajax post is not tested though

        }

        // This must be a hyperlink
        $(".saveCSV").on('click', function (event) {
            // CSV
            exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);

            // IF CSV, don't do event.preventDefault() or return false
            // We actually need this to be a typical hyperlink
        });
    });

PHP代码应该是

<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
$filename = $_POST['fname'];
echo $filename;
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>

OR

Blob blob = *// get Blob file *
byte [] bytes = blob.getBytes(1, (int) blob.length());
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Testing/";
File dir = new File(filePath);
File file = new File(dir, "filename.csv");
FileOutputStream fOut = new FileOutputStream(file);
//bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();