概要
バイブコーディングを利用して、ブラウザ上でCSVファイルを表示できる簡易CSVビューアを作成しました。
完成までかかった時間は30分ほどでした。
ライブラリには jQuery と DataTables を使用しています。
主な機能は以下の通りです。
・CSVファイルの読み込み
・行番号の自動表示
・ヘッダー表示、ソート機能、検索(フィルター)機能
・UTF-8 / Shift_JIS の自動判定
・CSVのダブルクォーテーション除去
主な使用技術
・HTML
・JavaScript
・jQuery
ソースコード
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>CSVビューア</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">
<style>
th { font-weight: bold; } /* ヘッダー太字 */
td:nth-child(1) { text-align: right; width: 40px; } /* 行番号列 */
</style>
</head>
<body>
<h1>CSVビューア</h1>
<input type="file" id="csvFile" accept=".csv">
<table id="csvTable" class="display" style="width:100%"></table>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script>
document.getElementById('csvFile').addEventListener('change', function(e){
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(ev){
const buffer = ev.target.result;
const bytes = new Uint8Array(buffer);
let text;
try {
// UTF-8で読込
text = new TextDecoder('utf-8', {fatal:true}).decode(bytes);
} catch(e) {
// UTF-8失敗ならShift_JIS
text = new TextDecoder('shift-jis').decode(bytes);
}
// BOM除去
text = text.replace(/^\uFEFF/, '');
const rows = text.trim()
.split(/\r?\n/)
.map(line =>
line.split(',')
.map(field =>
field.trim().replace(/^"(.*)"$/, '$1'))
);
const headers = rows.shift();
const data = rows.map((r,i)=> [i+1, ...r]);
const th = ['No', ...headers];
$('#csvTable').DataTable({
data: data,
columns: th.map(h => ({title:h})),
destroy: true,
paging: true,
searching: true,
info: true,
ordering: true
});
};
reader.readAsArrayBuffer(file);
});
</script>
</body>
</html>
実装内容
1. CSVファイルの読み込み
ファイル選択後、FileReaderを利用してCSVを読み込みます。
reader.readAsArrayBuffer(file);
ArrayBufferとして読み込むことで、文字コード判定を行えるようにしています
2. UTF-8 / Shift_JISの自動判定
Linux環境ではUTF-8、Windows環境ではShift_JISで作成されたCSVが多いため、両方に対応しました。
try {
text = new TextDecoder('utf-8', {fatal:true}).decode(bytes);
} catch(e) {
text = new TextDecoder('shift-jis').decode(bytes);
}
3. BOM(Byte Order Mark)除去
Excelで保存したUTF-8 CSVにはBOMが付与される場合があります。
text = text.replace(/^\uFEFF/, '');
不要なBOMを除去して文字化けを防止しています。
4. ダブルクォーテーション除去
CSVの各項目を表示する際、先頭と末尾のダブルクォーテーションを削除しています。
field.trim().replace(/^"(.*)"$/, '$1')
例えば、
"大阪"
"東京"
は
大阪
東京
として表示されます。
5. DataTablesによる一覧表示
DataTablesを利用することで、検索・ソート・ページング機能を簡単に実装できました。
$('#csvTable').DataTable({
data: data,
columns: th.map(h => ({title:h})),
paging: true,
searching: true,
ordering: true
});
作ってみた感想
バイブコーディングを利用することで、短時間で作成できた。
また、ExcelよりこのCSVビューアでCSVを開くのが楽だし、時間短縮につながると思う。