웹 페이지 에서 표 데이터 와 JSON 데 이 터 를 로 컬 엑셀 과 csv 파일 로 읽 기 (내 보 내기) 합 니 다.
6978 단어 WEB 프론트 엔 드
최근 실험실 에서 웹 엔 드 프로젝트 를 받 았 습 니 다. 자신 이 맡 은 모듈 은 파일 내 보 내기 작업 을 해 야 합 니 다.처음에는 표 의 내용 을 로 컬 엑셀 파일 로 내 보 내 고 JSON 데 이 터 를 로 컬 CSV 파일 로 내 보 내 는 것 을 요 구 했 습 니 다.다음은 각각 그들의 소스 코드 를 드 립 니 다.
표 내용 을 로 컬 엑셀 파일 로 내 보 냅 니 다.
var idTmr;
function getExplorer() {
var explorer = window.navigator.userAgent;
//ie
if (explorer.indexOf("MSIE") >= 0) {
return 'ie';
}
//firefox
else if (explorer.indexOf("Firefox") >= 0) {
return 'Firefox';
}
//Chrome
else if (explorer.indexOf("Chrome") >= 0) {
return 'Chrome';
}
//Opera
else if (explorer.indexOf("Opera") >= 0) {
return 'Opera';
}
//Safari
else if (explorer.indexOf("Safari") >= 0) {
return 'Safari';
}
}
function method1(tableid) {
if (getExplorer() == 'ie') {
var curTbl = document.getElementById(tableid);
var oXL = new ActiveXObject("Excel.Application");
var oWB = oXL.Workbooks.Add();
var xlsheet = oWB.Worksheets(1);
var sel = document.body.createTextRange();
sel.moveToElementText(curTbl);
sel.select();
sel.execCommand("Copy");
xlsheet.Paste();
oXL.Visible = true;
try {
var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
} catch (e) {
print("Nested catch caught " + e);
} finally {
oWB.SaveAs(fname);
oWB.Close(savechanges = false);
//xls.visible = false;
oXL.Quit();
oXL = null;
//window.setInterval("Cleanup();",1);
idTmr = window.setInterval("Cleanup();", 1);
}
}
else {
tableToExcel(tableid)
}
}
function Cleanup() {
window.clearInterval(idTmr);
CollectGarbage();
}
var tableToExcel = (function () {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '{table}
',
base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)))
},
format = function (s, c) {
return s.replace(/{(\w+)}/g,
function (m, p) {
return c[p];
})
}
return function (table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
코드 가 어렵 지 않 아서 알 기 쉽 습 니 다.
JSON 데 이 터 를 로 컬 CSV 파일 로 내 보 내기
var json2csv = function(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle;
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r
';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r
';
}
if (CSV == '') {
alert(" ");
return;
}
//Generate a file name
var fileName = " ";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g, "_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + encodeURI(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
,JSONData JSON ,ReportTitle ,
ShowLabel 。
,
var uri = 'data:text/csv;charset=utf-8,' + encodeURI(CSV); encodeURI CSV ,
espace , URL 。 encodeURI 。