online-csv-editor / script.js
edwardwongasd's picture
实现一个在线的csv编辑器,可以像excel一样编辑,由于csv文件行数和列数较多,200列10000行,需要支持筛选和冻结功能,还要支持查找功能,冻结是任意位置冻结,筛选是导入的csv首行左右表头筛选,要像IOS一样的设计
f51553f verified
Raw History Blame Contribute Delete
25.5 kB
/* eslint-disable no-undef */
// CSV Editor State and Logic
(() => {
// DOM references
const gridEl = document.getElementById('grid');
const datasetInfoEl = document.getElementById('datasetInfo');
const renderInfoEl = document.getElementById('renderInfo');
const fileInput = document.getElementById('fileInput');
const exportBtn = document.getElementById('exportBtn');
const clearBtn = document.getElementById('clearBtn');
const searchInput = document.getElementById('searchInput');
const caseSensitive = document.getElementById('caseSensitive');
const toggleFiltersBtn = document.getElementById('toggleFiltersBtn');
const resetFiltersBtn = document.getElementById('resetFiltersBtn');
const freezeLeftCount = document.getElementById('freezeLeftCount');
const applyFreezeBtn = document.getElementById('applyFreezeBtn');
const freezeRightCount = document.getElementById('freezeRightCount');
const applyFreezeRightBtn = document.getElementById('applyFreezeRightBtn');
// State
const state = {
rawHeaders: [],
headers: [],
rows: [], // Array<Array<string>>
allRows: [], // Original dataset (for reset)
colWidth: 120,
rowHeight: 32,
headerHeight: 40,
freezeLeft: 0,
freezeRight: 0,
filtersEnabled: false,
colFilters: {}, // { colIndex: Set(values) } include mode
globalSearch: '',
globalSearchRegex: null,
caseSensitive: false,
// render cache
totalWidth: 0,
nCols: 0,
nRows: 0,
lastSync: 0
};
// Utils
const debounce = (fn, ms = 250) => {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), ms);
};
};
function normalizeHeaders(headers) {
const result = [];
const seen = new Map();
for (let i = 0; i < headers.length; i++) {
let name = headers[i] != null ? String(headers[i]).trim() : `Column ${i+1}`;
if (name.length === 0) name = `Column ${i+1}`;
if (seen.has(name)) {
const count = seen.get(name) + 1;
seen.set(name, count);
name = `${name} (${count})`;
} else {
seen.set(name, 1);
}
result.push(name);
}
return result;
}
function computeUniqueSample(values, max = 2000) {
// Returns a Set of up to `max` unique values
const set = new Set();
for (const v of values) {
if (set.size >= max) break;
const s = v == null ? '' : String(v);
if (!set.has(s)) set.add(s);
}
return set;
}
function escapeCSV(value) {
const s = value == null ? '' : String(value);
if (/[",\n]/.test(s)) {
return `"${s.replace(/"/g, '""')}"`;
}
return s;
}
function toCSV(headers, rows) {
const lines = [];
lines.push(headers.map(escapeCSV).join(','));
for (const row of rows) {
lines.push(row.map(escapeCSV).join(','));
}
return lines.join('\n');
}
function recalcDimensions() {
state.nCols = state.headers.length;
state.nRows = state.rows.length;
state.totalWidth = state.nCols * state.colWidth;
const stickyLeftW = Math.min(state.freezeLeft, state.nCols) * state.colWidth;
const stickyRightW = Math.min(state.freezeRight, state.nCols) * state.colWidth;
document.documentElement.style.setProperty('--sticky-left-w', `${stickyLeftW}px`);
document.documentElement.style.setProperty('--sticky-right-w', `${stickyRightW}px`);
}
function updateDatasetInfo() {
const total = state.allRows.length;
const filtered = state.rows.length;
const filterActive = state.filtersEnabled || (state.globalSearch && state.globalSearch.length > 0);
datasetInfoEl.textContent = `${filtered} 行 × ${state.nCols} 列${filterActive ? `(共 ${total})` : ''}`;
}
// Filtering logic
function applyAllFilters() {
const start = performance.now();
const nCols = state.nCols;
const caseSensitive = state.caseSensitive;
const globalSearch = state.globalSearch || '';
let globalRegex = null;
if (globalSearch.length > 0) {
try {
globalRegex = new RegExp(globalSearch, caseSensitive ? '' : 'i');
} catch (e) {
renderInfoEl.textContent = '正则表达式错误';
return;
}
}
const colFilterEntries = Object.entries(state.colFilters);
// Pre-build col filter sets for speed
const colFilters = {};
for (const [idxStr, set] of colFilterEntries) {
const idx = Number(idxStr);
colFilters[idx] = new Set(set); // copy
}
const includeRow = (row) => {
// Column filter: row[j] must be in set for each filtered column j
for (const jStr in colFilters) {
const j = Number(jStr);
const val = row[j] == null ? '' : String(row[j]);
if (!colFilters[j].has(val)) return false;
}
// Global search: row includes the regex anywhere
if (globalRegex) {
let hit = false;
for (let j = 0; j < nCols; j++) {
const v = row[j] == null ? '' : String(row[j]);
if (globalRegex.test(v)) { hit = true; break; }
}
if (!hit) return false;
}
return true;
};
state.rows = state.allRows.filter(includeRow);
recalcDimensions();
updateDatasetInfo();
renderGrid(true);
const dur = Math.round(performance.now() - start);
renderInfoEl.textContent = `筛选用时 ${dur}ms`;
}
const applyAllFiltersDebounced = debounce(applyAllFilters, 200);
// Rendering
function clearGrid() {
gridEl.innerHTML = '';
}
function buildHeaderContent(scrollerEl, colStart, colEnd, isLeft = false, isRight = false) {
scrollerEl.innerHTML = '';
const headerRow = document.createElement('div');
headerRow.style.display = 'flex';
headerRow.style.alignItems = 'stretch';
headerRow.className = 'grid-header flex';
for (let j = colStart; j < colEnd; j++) {
const div = document.createElement('div');
div.className = `grid-cell flex items-center justify-between px-2 ${isLeft || isRight ? 'sticky-left' : ''} ${j === state.freezeLeft - 1 ? 'frozen-edge' : ''} ${j === state.nCols - state.freezeRight ? 'frozen-edge' : ''}`;
div.dataset.col = String(j);
const title = document.createElement('div');
title.className = 'truncate text-xs font-medium text-slate-700';
title.textContent = state.headers[j];
const actions = document.createElement('div');
actions.className = 'flex items-center gap-1';
const filterBtn = document.createElement('button');
filterBtn.className = 'btn-ghost p-1 rounded';
filterBtn.title = '筛选该列';
filterBtn.innerHTML = `
<svg class="w-4 h-4 text-slate-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 5h18M6 12h12M10 19h4"/>
</svg>`;
filterBtn.addEventListener('click', (e) => {
e.stopPropagation();
toggleFilterPopover(j, filterBtn);
});
actions.appendChild(filterBtn);
div.appendChild(title);
div.appendChild(actions);
headerRow.appendChild(div);
}
scrollerEl.appendChild(headerRow);
}
function toggleFilterPopover(colIndex, anchorEl) {
// Close existing popover
const existing = document.querySelector('.popover[data-role="filter-popover"]');
if (existing) existing.remove();
if (!state.filtersEnabled) {
// enable and apply
state.filtersEnabled = true;
}
const rect = anchorEl.getBoundingClientRect();
const pop = document.createElement('div');
pop.className = 'popover w-80 p-3';
pop.dataset.role = 'filter-popover';
pop.style.left = `${Math.max(8, rect.left - 260)}px`;
pop.style.top = `${Math.min(window.innerHeight - 320, rect.bottom + 8)}px`;
// Build unique set from original data for better fidelity
const uniques = new Set();
for (const row of state.allRows) {
const v = row[colIndex] == null ? '' : String(row[colIndex]);
uniques.add(v);
if (uniques.size > 2000) break;
}
const current = state.colFilters[colIndex] || new Set();
const header = document.createElement('div');
header.className = 'flex items-center justify-between mb-2';
header.innerHTML = `
<div class="font-medium text-sm text-slate-700">筛选列:${state.headers[colIndex]}</div>
<button class="btn-ghost p-1" data-action="close">
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/></svg>
</button>`;
const search = document.createElement('input');
search.className = 'input mb-2';
search.placeholder = '搜索选项...';
const listWrap = document.createElement('div');
listWrap.className = 'border border-slate-200 rounded-lg max-h-60 overflow-auto';
const list = document.createElement('div');
listWrap.appendChild(list);
function renderList() {
list.innerHTML = '';
const term = search.value.trim().toLowerCase();
const values = Array.from(uniques).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
let count = 0;
for (const v of values) {
const show = term.length === 0 || String(v).toLowerCase().includes(term);
if (!show) continue;
count++;
if (count > 1000) { // safety
break;
}
const rowEl = document.createElement('label');
rowEl.className = 'flex items-center gap-2 px-3 py-2 hover:bg-slate-50';
rowEl.innerHTML = `
<input type="checkbox" class="rounded border-slate-300 text-primary focus:ring-primary" ${current.has(v) ? 'checked' : ''}/>
<span class="flex-1 truncate">${v === '' ? '<空>' : v}</span>
<span class="text-xs text-slate-400">包含</span>
`;
const checkbox = rowEl.querySelector('input[type=checkbox]');
checkbox.addEventListener('change', () => {
const set = state.colFilters[colIndex] || new Set();
if (checkbox.checked) set.add(v);
else set.delete(v);
if (set.size === 0) delete state.colFilters[colIndex];
else state.colFilters[colIndex] = set;
applyAllFiltersDebounced();
});
list.appendChild(rowEl);
}
if (count === 0) {
const empty = document.createElement('div');
empty.className = 'p-3 text-sm text-slate-500';
empty.textContent = '无匹配项';
list.appendChild(empty);
}
}
search.addEventListener('input', renderList);
const footer = document.createElement('div');
footer.className = 'flex items-center gap-2 mt-3';
const btnAll = document.createElement('button');
btnAll.className = 'btn';
btnAll.textContent = '全选';
btnAll.addEventListener('click', () => {
state.colFilters[colIndex] = new Set(uniques);
renderList();
applyAllFiltersDebounced();
});
const btnNone = document.createElement('button');
btnNone.className = 'btn';
btnNone.textContent = '清空';
btnNone.addEventListener('click', () => {
delete state.colFilters[colIndex];
renderList();
applyAllFiltersDebounced();
});
footer.appendChild(btnAll);
footer.appendChild(btnNone);
pop.appendChild(header);
pop.appendChild(search);
pop.appendChild(listWrap);
pop.appendChild(footer);
header.querySelector('[data-action="close"]').addEventListener('click', () => pop.remove());
document.body.appendChild(pop);
renderList();
}
function renderGrid(forceRebuild = false) {
clearGrid();
if (state.nCols === 0 || state.nRows === 0) {
const empty = document.createElement('div');
empty.className = 'p-8 text-center text-slate-500';
empty.innerHTML = '暂无数据。请导入 CSV 文件。';
gridEl.appendChild(empty);
return;
}
const viewport = gridEl.getBoundingClientRect();
const viewWidth = Math.max(320, viewport.width);
const viewHeight = Math.max(300, window.innerHeight - 300);
// Set CSS vars
document.documentElement.style.setProperty('--header-h', `${state.headerHeight}px`);
document.documentElement.style.setProperty('--row-h', `${state.rowHeight}px`);
document.documentElement.style.setProperty('--cell-w', `${state.colWidth}px`);
// Layout:
// Two rows: header row and body row.
// Each row has three panes: left sticky, middle scrollable, right sticky.
const headerRow = document.createElement('div');
headerRow.className = 'flex w-full';
const bodyRow = document.createElement('div');
bodyRow.className = 'flex w-full';
// Measure visible columns
// For simplicity, we'll render a virtual window horizontally across all columns (like vertically),
// but we still split into left/middle/right panes so frozen columns are visible.
const totalCols = state.nCols;
const colWidth = state.colWidth;
const stickyLeftW = Math.min(state.freezeLeft, totalCols) * colWidth;
const stickyRightW = Math.min(state.freezeRight, totalCols) * colWidth;
const allColsRange = [0, totalCols];
// Header containers
const headerLeft = document.createElement('div');
headerLeft.className = 'sticky-left border-r';
headerLeft.style.width = `${stickyLeftW}px`;
const headerScroll = document.createElement('div');
headerScroll.className = 'header-scroller overflow-x-auto overflow-y-hidden border-r';
headerScroll.style.flex = '1 1 auto';
const headerRight = document.createElement('div');
headerRight.className = 'sticky-right';
headerRight.style.width = `${stickyRightW}px`;
// Body containers
const bodyLeft = document.createElement('div');
bodyLeft.className = 'sticky-left border-r';
bodyLeft.style.width = `${stickyLeftW}px`;
const bodyScroll = document.createElement('div');
bodyScroll.className = 'row-scroller overflow-auto';
bodyScroll.style.flex = '1 1 auto';
const bodyRight = document.createElement('div');
bodyRight.className = 'sticky-right';
bodyRight.width = `${stickyRightW}px`;
bodyRight.style.width = `${stickyRightW}px`;
// Build content
buildHeaderContent(headerLeft, 0, Math.min(state.freezeLeft, totalCols), true, false);
buildHeaderContent(headerScroll, 0, totalCols, false, false);
buildHeaderContent(headerRight, Math.max(0, totalCols - state.freezeRight), totalCols, false, true);
// Body virtual content
const spacer = document.createElement('div');
spacer.style.width = `${state.totalWidth}px`;
spacer.style.height = `${state.nRows * state.rowHeight}px`;
spacer.style.position = 'relative';
function renderVisibleRows() {
// Clean existing cells
headerLeft.innerHTML = '';
headerScroll.innerHTML = '';
headerRight.innerHTML = '';
bodyLeft.innerHTML = '';
bodyRight.innerHTML = '';
spacer.innerHTML = '';
// Rebuild headers (fast)
buildHeaderContent(headerLeft, 0, Math.min(state.freezeLeft, totalCols), true, false);
buildHeaderContent(headerScroll, 0, totalCols, false, false);
buildHeaderContent(headerRight, Math.max(0, totalCols - state.freezeRight), totalCols, false, true);
// Visible rows by scroll
const y = bodyScroll.scrollTop;
const x = bodyScroll.scrollLeft;
const startRow = Math.max(0, Math.floor(y / state.rowHeight) - 10);
const endRow = Math.min(state.nRows, startRow + Math.ceil(viewHeight / state.rowHeight) + 20);
const topOffset = startRow * state.rowHeight;
// Build left frozen rows
const leftFrag = document.createDocumentFragment();
for (let r = startRow; r < endRow; r++) {
const rowLeft = document.createElement('div');
rowLeft.className = 'flex';
rowLeft.style.position = 'absolute';
rowLeft.style.top = `${r * state.rowHeight}px`;
rowLeft.style.height = `${state.rowHeight}px`;
for (let j = 0; j < Math.min(state.freezeLeft, totalCols); j++) {
rowLeft.appendChild(buildCell(r, j, true, false));
}
leftFrag.appendChild(rowLeft);
}
// Build middle rows (all columns)
const midFrag = document.createDocumentFragment();
for (let r = startRow; r < endRow; r++) {
const rowDiv = document.createElement('div');
rowDiv.className = 'flex';
rowDiv.style.position = 'absolute';
rowDiv.style.top = `${r * state.rowHeight}px`;
rowDiv.style.height = `${state.rowHeight}px`;
for (let j = 0; j < totalCols; j++) {
rowDiv.appendChild(buildCell(r, j, false, false));
}
midFrag.appendChild(rowDiv);
}
// Build right frozen rows
const rightFrag = document.createDocumentFragment();
for (let r = startRow; r < endRow; r++) {
const rowRight = document.createElement('div');
rowRight.className = 'flex';
rowRight.style.position = 'absolute';
rowRight.style.top = `${r * state.rowHeight}px`;
rowRight.style.height = `${state.rowHeight}px`;
const rightStart = Math.max(0, totalCols - state.freezeRight);
for (let j = rightStart; j < totalCols; j++) {
rowRight.appendChild(buildCell(r, j, false, true));
}
rightFrag.appendChild(rowRight);
}
bodyLeft.appendChild(leftFrag);
spacer.appendChild(midFrag);
bodyRight.appendChild(rightFrag);
}
function buildCell(r, c, isLeft, isRight) {
const div = document.createElement('div');
div.className = `grid-cell flex items-center px-2 ${isLeft ? 'sticky-left' : ''} ${isRight ? 'sticky-right' : ''} ${c === state.freezeLeft - 1 ? 'frozen-edge' : ''} ${c === state.nCols - state.freezeRight ? 'frozen-edge' : ''}`;
div.dataset.row = String(r);
div.dataset.col = String(c);
const val = state.rows[r][c] == null ? '' : String(state.rows[r][c]);
const span = document.createElement('div');
span.className = 'truncate text-[13px] text-slate-800 w-full';
span.textContent = val;
div.appendChild(span);
// Edit on double click or enter
div.tabIndex = -1;
div.addEventListener('dblclick', () => startEdit(div));
div.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
startEdit(div);
}
});
return div;
}
function startEdit(cellEl) {
const r = Number(cellEl.dataset.row);
const c = Number(cellEl.dataset.col);
const original = state.rows[r][c] == null ? '' : String(state.rows[r][c]);
const input = document.createElement('input');
input.type = 'text';
input.value = original;
input.className = 'input w-full h-full border-0 outline-none bg-transparent px-0';
cellEl.innerHTML = '';
cellEl.appendChild(input);
cellEl.classList.add('cell-editing');
input.focus();
input.setSelectionRange(original.length, original.length);
const commit = () => {
state.rows[r][c] = input.value;
cellEl.classList.remove('cell-editing');
const span = document.createElement('div');
span.className = 'truncate text-[13px] text-slate-800 w-full';
span.textContent = input.value;
cellEl.innerHTML = '';
cellEl.appendChild(span);
renderInfoEl.textContent = `已编辑单元格 (${r + 1}, ${c + 1})`;
};
input.addEventListener('blur', commit, { once: true });
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
input.blur();
} else if (e.key === 'Escape') {
e.preventDefault();
cellEl.classList.remove('cell-editing');
const span = document.createElement('div');
span.className = 'truncate text-[13px] text-slate-800 w-full';
span.textContent = original;
cellEl.innerHTML = '';
cellEl.appendChild(span);
}
});
}
// Assemble
headerRow.appendChild(headerLeft);
headerRow.appendChild(headerScroll);
headerRow.appendChild(headerRight);
bodyRow.appendChild(bodyLeft);
bodyRow.appendChild(bodyScroll);
bodyRow.appendChild(bodyRight);
gridEl.appendChild(headerRow);
gridEl.appendChild(bodyRow);
bodyScroll.appendChild(spacer);
// Sync scroll
const syncHorizontal = (src, dests) => {
src.addEventListener('scroll', () => {
for (const d of dests) d.scrollLeft = src.scrollLeft;
});
};
syncHorizontal(bodyScroll, [headerScroll]);
syncHorizontal(headerScroll, [bodyScroll]);
// Initial render of visible rows
renderVisibleRows();
// Render on scroll with rAF
let ticking = false;
const onScroll = () => {
if (!ticking) {
requestAnimationFrame(() => {
renderVisibleRows();
ticking = false;
});
ticking = true;
}
};
bodyScroll.addEventListener('scroll', onScroll);
window.addEventListener('resize', debounce(() => {
renderVisibleRows();
}, 100));
renderInfoEl.textContent = `可见行渲染范围取决于滚动位置`;
}
// Data import
function importCSVFromFile(file) {
renderInfoEl.textContent = '正在解析 CSV...';
Papa.parse(file, {
worker: true,
skipEmptyLines: 'greedy',
delimiter: '', // auto-detect
complete: (res) => {
if (res.errors && res.errors.length) {
console.warn('CSV parse errors:', res.errors.slice(0, 5));
}
let data = res.data;
// Trim trailing empty rows
while (data.length && data[data.length - 1].every(v => String(v).trim() === '')) {
data.pop();
}
if (data.length === 0) {
renderInfoEl.textContent = 'CSV 为空';
return;
}
// Assume first row as header
const rawHeaders = data[0].map(v => v == null ? '' : String(v));
const headers = normalizeHeaders(rawHeaders);
const rows = data.slice(1).map(row => {
const arr = new Array(headers.length);
for (let i = 0; i < headers.length; i++) {
arr[i] = row[i] == null ? '' : String(row[i]);
}
return arr;
});
state.rawHeaders = rawHeaders;
state.headers = headers;
state.allRows = rows;
state.rows = rows.slice();
state.filtersEnabled = false;
state.colFilters = {};
state.globalSearch = '';
state.freezeLeft = 0;
state.freezeRight = 0;
recalcDimensions();
updateDatasetInfo();
renderGrid(true);
renderInfoEl.textContent = `已加载 ${rows.length} 行 × ${headers.length} 列`;
// Update freeze inputs
freezeLeftCount.value = state.freezeLeft;
freezeRightCount.value = state.freezeRight;
searchInput.value = '';
},
error: (err) => {
console.error(err);
renderInfoEl.textContent = 'CSV 解析失败';
}
});
}
// Events
fileInput.addEventListener('change', (e) => {
const file = e.target.files?.[0];
if (file) importCSVFromFile(file);
fileInput.value = '';
});
exportBtn.addEventListener('click', () => {
if (state.nCols === 0) {
renderInfoEl.textContent = '没有可导出的数据';
return;
}
const csv = toCSV(state.headers, state.rows);
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'export.csv';
a.click();
URL.revokeObjectURL(a.href);
});
clearBtn.addEventListener('click', () => {
state.rawHeaders = [];
state.headers = [];
state.rows = [];
state.allRows = [];
state.nCols = 0;
state.nRows = 0;
state.filtersEnabled = false;
state.colFilters = {};
state.globalSearch = '';
state.freezeLeft = 0;
state.freezeRight = 0;
searchInput.value = '';
freezeLeftCount.value = 0;
freezeRightCount.value = 0;
clearGrid();
updateDatasetInfo();
renderInfoEl.textContent = '已清空';
});
searchInput.addEventListener('input', debounce(() => {
state.globalSearch = searchInput.value || '';
applyAllFiltersDebounced();
}, 200));
caseSensitive.addEventListener('change', () => {
state.caseSensitive = caseSensitive.checked;
applyAllFiltersDebounced();
});
toggleFiltersBtn.addEventListener('click', () => {
state.filtersEnabled = !state.filtersEnabled;
applyAllFiltersDebounced();
});
resetFiltersBtn.addEventListener('click', () => {
state.filtersEnabled = false;
state.colFilters = {};
state.globalSearch = '';
searchInput.value = '';
applyAllFilters();
renderInfoEl.textContent = '筛选已重置';
});
applyFreezeBtn.addEventListener('click', () => {
let n = Number(freezeLeftCount.value || 0);
if (!Number.isFinite(n) || n < 0) n = 0;
n = Math.min(n, state.nCols);
state.freezeLeft = n;
recalcDimensions();
renderGrid(true);
});
applyFreezeRightBtn.addEventListener('click', () => {
let n = Number(freezeRightCount.value || 0);
if (!Number.isFinite(n) || n < 0) n = 0;
n = Math.min(n, state.nCols);
state.freezeRight = n;
recalcDimensions();
renderGrid(true);
});