我目前正在修复 Web 应用程序上数据表的 CSV 导出。 当您单击导出按钮时,它目前能够在除 Chrome 之外的所有需要的浏览器上导出。 一段时间以来,我一直在努力弄明白这个问题,但我一直在抗拒拔头发。
下面的代码是我最近才使用的服务。非常感谢任何帮助。
svc.downloadContent =
(target, fileName, content) => {
if (!browserSvc.canDownloadFiles()) return;
// IE10
if (window.navigator.msSaveOrOpenBlob) {
const blob = new Blob([content], {type: 'text/csv'});
window.navigator.msSaveOrOpenBlob(blob, fileName);
// IE9
} else if (env.browser === 'Explorer') {
const frame = document.createElement('iframe');
document.body.appendChild(frame);
angular.element(frame).hide();
const cw = frame.contentWindow;
const cwDoc = cw.document;
cwDoc.open('text/csv', 'replace');
cwDoc.write(content);
cwDoc.close();
cw.focus();
cwDoc.execCommand('SaveAs', true, fileName);
document.body.removeChild(frame);
// Sane browsers
} else {
const blob = new Blob([content], {type: 'text/csv'});
const url = URL.createObjectURL(blob);
const a = angular.element(target);
const download = a.attr('download');
// If not already downloading ...
if (!download) {
a.attr('download', fileName);
a.attr('href', url);
// This must run in the next tick to avoid
// "$digest already in progress" error.
//$timeout(() => target.click());
try {
target.click();
// Clear attributes to prepare for next download.
a.attr('download', '');
a.attr('href', '');
} catch (e) {
console.error('csv-svc.js: e =', e);
}
}
}
最佳答案
我在发布问题后几分钟就设法解决了这个问题。如果只是为了 Chrome,我需要添加一个 else。但是,我会发布修复程序并保留它,希望它能在将来帮助其他人。
else if (env.browser === 'Chrome') {
const blob = new Blob([content], {type: 'text/csv'});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.style = 'visibility:hidden';
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
关于javascript - Chrome 中表格的 CSV 导出不起作用 - JavaScript/AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36898798/