Skip to content

Instantly share code, notes, and snippets.

@GZShi
Last active April 19, 2017 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GZShi/5e90bbd79c5d18efd614aa2cf581ff11 to your computer and use it in GitHub Desktop.
Save GZShi/5e90bbd79c5d18efd614aa2cf581ff11 to your computer and use it in GitHub Desktop.
简易的CSV转换,将字段强制加上双引号
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>CSV 双引号转化</title>
<style>
.drop-area {
padding: 3em;
margin: 3em;
border: 1px dashed gray;
text-align: center;
}
</style>
</head>
<body>
<div class="drop-area" id="drop-area">
<p>将 CSV 文件拖拽到此处</p>
<p>注意:字段里面不能包含半角逗号</p>
</div>
<div class="info" id="info-area"></div>
<script>
if (supportDetect()) {
let dropArea = document.querySelector('#drop-area');
let infoArea = document.querySelector('#info-area')
dropArea.addEventListener('drop', event => {
event.stopPropagation();
event.preventDefault();
let files = Array.prototype.slice.apply(event.dataTransfer.files);
let html = files.map((file, index) => `<p>${file.name} - ${file.size}bytes <span id="file-state-${index}">正在处理</span></p>`).join('');
infoArea.innerHTML = html;
files.forEach((file, index) => {
let reader = new FileReader();
reader.onload = function(ev) {
let text = this.result;
let newContent = convertCSV(text);
let blob = new Blob([newContent], {
type: 'text/plain'
});
let uri = URL.createObjectURL(blob);
document.querySelector(`span#file-state-${index}`).innerHTML = `<a href="${uri}" download="${file.name}">下载</a>`;
};
reader.readAsText(file);
});
}, false);
dropArea.addEventListener('dragover', event => {
event.stopPropagation();
event.preventDefault();
event.dataTransfer.dragEffect = 'copy';
}, false);
}
function convertCSV(content) {
let CRLF = '\r\n';
let rows = content.split(CRLF);
if (rows.length > 1 && rows[rows.length - 1] === "") rows.pop();
let newContent = rows.map(row => {
let items = row.split(',');
return items.map(item => {
if (item[0] === '"' && item[item.length - 1] === '"') return item;
else return `"${item.replace(/\"/g, '""')}"`;
}).join(',');
}).join(CRLF);
return newContent;
}
function supportDetect() {
try {
let blob = new Blob([], {
type: 'text/plain'
});
let reader = new FileReader();
let body = document.querySelector('body');
} catch (ex) {
document.getElementById('drop-area').innerHTML = '您的浏览器不支持 HTML5 的 API,请使用最新的 Chrome、Firefox 或 IE';
return false;
}
return true;
}
var es6Support = true;
</script>
<script>
var es6Support = es6Support || false;
if (!es6Support) {
document.getElementById('drop-area').innerHTML = '<span style="color: red">您的浏览器不支持 ES6 标准,请使用最新的 Chrome、Firefox 或 IE</span>'
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment