-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv.php
More file actions
378 lines (322 loc) · 12 KB
/
Copy pathcsv.php
File metadata and controls
378 lines (322 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
<?php
$pageTitle = 'CSV Analyzer & Statistics — BI Data Tools';
$pageDescription = 'Анализ CSV файлов: статистика, валидация структуры, профилирование данных.';
include('../header.php'); ?>
<h1><i class="fas fa-table"></i> CSV Analyzer & Statistics</h1>
<div class="tool-container csv-analyzer">
<div class="tool-section">
<p>Анализ CSV файлов: статистика, валидация структуры, профилирование данных.</p>
<div class="upload-area" id="uploadArea">
<i class="fas fa-cloud-upload-alt" style="font-size: 2rem; color: var(--primary-color); margin-bottom: 1rem;"></i>
<p>Перетащите CSV файл сюда или нажмите для выбора</p>
<input type="file" id="fileInput" accept=".csv" style="display: none;" autofocus>
</div>
<div class="form-group">
<label for="delimiter">Разделитель:</label>
<select id="delimiter" class="form-control" style="font-family: inherit;">
<option value=",">Запятая (,)</option>
<option value=";">Точка с запятой (;)</option>
<option value="\t">Табуляция (\t)</option>
<option value="|">Вертикальная черта (|)</option>
</select>
</div>
<div style="margin: 1.5rem 0;">
<button id="analyze" class="btn" aria-label="Анализировать CSV">Анализировать CSV ▶</button>
<button id="download" class="btn btn-sm" style="display: none;" aria-label="Скачать обработанный файл">Скачать обработанный файл</button>
</div>
<div id="err" class="error-message"></div>
<div id="success" class="success-message"></div>
<div id="loading" style="display:none; color:var(--primary-color); font-weight:bold;">Загрузка/обработка...</div>
<div id="stats" class="stats-grid" style="display: none;"></div>
<div id="preview" style="display: none;">
<h4>Предпросмотр данных (первые 10 строк):</h4>
<div id="previewTable"></div>
</div>
</div>
</div>
<script>
const $ = id => document.getElementById(id);
let csvData = null;
let processedData = null;
// File upload handling
const uploadArea = $('uploadArea');
const fileInput = $('fileInput');
uploadArea.onclick = () => fileInput.click();
uploadArea.ondragover = (e) => {
e.preventDefault();
uploadArea.classList.add('dragover');
};
uploadArea.ondragleave = () => {
uploadArea.classList.remove('dragover');
};
uploadArea.ondrop = (e) => {
e.preventDefault();
uploadArea.classList.remove('dragover');
const files = e.dataTransfer.files;
if (files.length > 0) {
handleFile(files[0]);
}
};
fileInput.onchange = (e) => {
if (e.target.files.length > 0) {
handleFile(e.target.files[0]);
}
};
function handleFile(file) {
if (!file.name.toLowerCase().endsWith('.csv')) {
$('err').textContent = 'Пожалуйста, выберите CSV файл';
return;
}
const reader = new FileReader();
reader.onload = (e) => {
csvData = e.target.result;
$('success').textContent = `✓ Файл "${file.name}" загружен (${formatFileSize(file.size)})`;
$('err').textContent = '';
};
reader.readAsText(file, 'UTF-8');
}
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
function parseCSV(csvText, delimiter = ',') {
const lines = csvText.trim().split('\n').filter(line => line.trim());
if (lines.length === 0) {
throw new Error('CSV файл пуст');
}
// More robust CSV parsing that handles quoted values with commas
function parseCSVLine(line, delimiter) {
const result = [];
let current = '';
let inQuotes = false;
let i = 0;
while (i < line.length) {
const char = line[i];
if (char === '"') {
if (inQuotes && line[i + 1] === '"') {
// Escaped quote
current += '"';
i += 2;
} else {
// Toggle quote state
inQuotes = !inQuotes;
i++;
}
} else if (char === delimiter && !inQuotes) {
// End of field
result.push(current.trim());
current = '';
i++;
} else {
current += char;
i++;
}
}
// Add the last field
result.push(current.trim());
return result;
}
try {
const headers = parseCSVLine(lines[0], delimiter)
.map(h => h.replace(/^"|"$/g, '').trim())
.filter(h => h); // Remove empty headers
if (headers.length === 0) {
throw new Error('Не найдены заголовки столбцов');
}
const rows = [];
const errors = [];
for (let i = 1; i < lines.length; i++) {
try {
const values = parseCSVLine(lines[i], delimiter)
.map(v => v.replace(/^"|"$/g, '').trim());
if (values.length !== headers.length) {
errors.push(`Строка ${i + 1}: неверное количество столбцов (ожидается ${headers.length}, получено ${values.length})`);
continue;
}
const row = {};
headers.forEach((header, index) => {
row[header] = values[index] || '';
});
rows.push(row);
} catch (lineError) {
errors.push(`Строка ${i + 1}: ${lineError.message}`);
}
}
if (rows.length === 0) {
throw new Error('Не удалось обработать ни одной строки данных');
}
// Show warnings if there were errors
if (errors.length > 0) {
console.warn('CSV parsing warnings:', errors);
$('err').textContent = `Предупреждения: ${errors.length} строк пропущено из-за ошибок форматирования`;
}
return { headers, rows, errors };
} catch (error) {
throw new Error(`Ошибка парсинга CSV: ${error.message}`);
}
}
function analyzeData(data) {
const stats = {
totalRows: data.rows.length,
totalColumns: data.headers.length,
columnStats: {}
};
data.headers.forEach(header => {
const values = data.rows.map(row => row[header]).filter(v => v && v.trim());
const uniqueValues = [...new Set(values)];
// Detect data type
let dataType = 'string';
if (values.every(v => !isNaN(v) && !isNaN(parseFloat(v)))) {
dataType = values.every(v => Number.isInteger(parseFloat(v))) ? 'integer' : 'number';
} else if (values.every(v => /^\d{4}-\d{2}-\d{2}/.test(v))) {
dataType = 'date';
} else if (values.every(v => /^(true|false|yes|no|1|0)$/i.test(v))) {
dataType = 'boolean';
}
stats.columnStats[header] = {
dataType,
totalValues: data.rows.length,
nonEmptyValues: values.length,
emptyValues: data.rows.length - values.length,
uniqueValues: uniqueValues.length,
duplicates: values.length - uniqueValues.length
};
});
return stats;
}
function displayStats(stats) {
const statsContainer = $('stats');
statsContainer.innerHTML = '';
// Overall stats
const overallStats = [
{ title: 'Всего строк', value: stats.totalRows },
{ title: 'Всего колонок', value: stats.totalColumns },
{ title: 'Размер данных', value: `${stats.totalRows * stats.totalColumns} ячеек` }
];
overallStats.forEach(stat => {
const card = document.createElement('div');
card.className = 'stat-card';
card.innerHTML = `
<h4>${stat.title}</h4>
<div class="value">${stat.value}</div>
`;
statsContainer.appendChild(card);
});
// Column stats table
const table = document.createElement('table');
table.className = 'preview-table';
table.style.gridColumn = '1 / -1';
table.style.marginTop = '2rem';
const thead = document.createElement('thead');
thead.innerHTML = `
<tr>
<th>Колонка</th>
<th>Тип данных</th>
<th>Заполнено</th>
<th>Пустые</th>
<th>Уникальные</th>
<th>Дубликаты</th>
</tr>
`;
table.appendChild(thead);
const tbody = document.createElement('tbody');
Object.entries(stats.columnStats).forEach(([column, stat]) => {
const row = document.createElement('tr');
row.innerHTML = `
<td><strong>${column}</strong></td>
<td>${stat.dataType}</td>
<td>${stat.nonEmptyValues}</td>
<td>${stat.emptyValues}</td>
<td>${stat.uniqueValues}</td>
<td>${stat.duplicates}</td>
`;
tbody.appendChild(row);
});
table.appendChild(tbody);
statsContainer.appendChild(table);
statsContainer.style.display = 'grid';
}
function displayPreview(data) {
const previewContainer = $('previewTable');
const table = document.createElement('table');
table.className = 'preview-table';
// Headers
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
data.headers.forEach(header => {
const th = document.createElement('th');
th.textContent = header;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// Data rows (first 10)
const tbody = document.createElement('tbody');
data.rows.slice(0, 10).forEach(row => {
const tr = document.createElement('tr');
data.headers.forEach(header => {
const td = document.createElement('td');
td.textContent = row[header] || '';
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
previewContainer.innerHTML = '';
previewContainer.appendChild(table);
$('preview').style.display = 'block';
}
$('analyze').onclick = () => {
$('err').textContent = '';
$('success').textContent = '';
$('loading').style.display = 'block';
setTimeout(() => {
if (!csvData) {
$('err').textContent = 'Загрузите CSV файл для анализа';
$('loading').style.display = 'none';
return;
}
try {
const delimiter = $('delimiter').value === '\\t' ? '\t' : $('delimiter').value;
const data = parseCSV(csvData, delimiter);
if (data.rows.length === 0) {
$('err').textContent = 'CSV файл не содержит данных или имеет неверный формат';
$('loading').style.display = 'none';
return;
}
processedData = data;
const stats = analyzeData(data);
displayStats(stats);
displayPreview(data);
$('success').textContent = '✓ Анализ завершен успешно';
$('download').style.display = 'inline-block';
} catch (e) {
$('err').textContent = 'Ошибка при анализе CSV: ' + e.message;
}
$('loading').style.display = 'none';
}, 100);
};
$('download').onclick = () => {
if (!processedData) return;
// Create cleaned CSV
const delimiter = $('delimiter').value === '\\t' ? '\t' : $('delimiter').value;
let csv = processedData.headers.join(delimiter) + '\n';
processedData.rows.forEach(row => {
const values = processedData.headers.map(header => {
const value = row[header] || '';
return value.includes(delimiter) ? `"${value}"` : value;
});
csv += values.join(delimiter) + '\n';
});
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'processed_data.csv';
link.click();
URL.revokeObjectURL(link.href);
};
</script>
<?php include('footer.php'); ?>