gpt4 book ai didi

javascript - 在 Electron 中将 HTMLtable 导出为 CSV

转载 作者:可可西里 更新时间:2023-11-01 13:45:47 28 4
gpt4 key购买 nike

我正在制作一个 Electron 应用程序(使用 Node Js),我需要将 HTML 表格数据导出到 .csv 文件。我关注了this教程来实现这一点。我使用的函数如下。

$(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) + '"';

// Deliberate 'false', see comment below
if (false && window.navigator.msSaveBlob) {
var blob = new Blob([decodeURIComponent(csv)], {
type: 'text/csv;charset=utf8'
});

window.navigator.msSaveBlob(blob, filename);
} else if (window.Blob && window.URL) {
// HTML5 Blob
var blob = new Blob([csv], { type: 'text/csv;charset=utf8' });
var csvUrl = URL.createObjectURL(blob);

$(this).attr({
'download': filename,
'href': csvUrl
});
} else {
// Data URI
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

$(this).attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
}

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

exportTableToCSV.apply(this, args);

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

对于输出的 csv 文件,我给了一个默认名称“export.csv”。

我面临的问题如下。

当我在 Windows 中运行这个 Electron 应用程序时(我使用 electron-packager 打包它,Ubuntu 是我的主机),

在出现的 Windows 对话框中询问我将文档保存在何处 enter image description here

如果我不更改“文件名”字段中的默认名称“export.csv”,我会得到一个有效的 export.csv 文件作为输出。下面附上截图以供引用

enter image description here

但是如果我将“文件名”字段中的名称更改为不同的名称(例如:temp),我不会得到 .csv 文件。相反,我得到了一个如下图所示的文件。

enter image description here

谁能告诉我如何才能获得有效的 .csv 文件作为我的输出文件,即使用户更改了输出“文件名”?

最佳答案

您没有显示用于显示 Windows 对话框的代码,但我认为最简单的做法是将其默认为 .csv 扩展名。

您可以通过在对 showSaveDialog 的调用中设置 filters 来做到这一点。

例如:

var filename = dialog.showSaveDialog({
filters: [
{ name: 'CSV files', extensions: ['csv'] }
]
});

这样,当用户输入自己的文件名时,结果将默认为 .csv 扩展名。

关于javascript - 在 Electron 中将 HTMLtable 导出为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43799640/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com