gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
Здача сделать из exel таблицу html. Используй бутстрап, php, сделай максимально…
- User
Здача сделать из exel таблицу html. Используй бутстрап, php, сделай максимально универсальный скрипт
- Assistant
Здача сделать из exel таблицу html. Используй бутстрап, php, сделай максимально универсальный скрипт
Конечно! Ниже приведён максимально универсальный PHP-скрипт, который принимает на вход Excel-файл (.xls, .xlsx), считывает его содержимое и выводит таблицу с помощью Bootstrap для красивого отображения.
php_zip, php_xml и php_mbstring для работы с PHPExcel или PhpSpreadsheet.PhpSpreadsheet.phpoffice/phpspreadsheet через Composer:composer require phpoffice/phpspreadsheet
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
function excelToHtmlTable($filePath)
{
// Загружаем файл
$spreadsheet = IOFactory::load($filePath);
$html = '';
// Получаем все листы
foreach ($spreadsheet->getAllSheets() as $sheet) {
$title = htmlspecialchars($sheet->getTitle());
$html .= "<h3>Таблица: {$title}</h3>";
$html .= '<div class="table-responsive"><table class="table table-bordered table-striped table-hover">';
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
// Для заголовка таблицы возьмём первую строку
$html .= '<thead><tr>';
for ($col = 1; $col <= $highestColumnIndex; $col++) {
$cellValue = $sheet->getCellByColumnAndRow($col, 1)->getFormattedValue();
$html .= '<th>' . htmlspecialchars($cellValue) . '</th>';
}
$html .= '</tr></thead>';
// Тело таблицы - со второй строки и дальше
$html .= '<tbody>';
for ($row = 2; $row <= $highestRow; $row++) {
$html .= '<tr>';
for ($col = 1; $col <= $highestColumnIndex; $col++) {
$cellValue = $sheet->getCellByColumnAndRow($col, $row)->getFormattedValue();
$html .= '<td>' . htmlspecialchars($cellValue) . '</td>';
}
$html .= '</tr>';
}
$html .= '</tbody>';
$html .= '</table></div>';
}
return $html;
}
// Обработка загрузки файла через форму
$htmlTable = '';
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['excel_file'])) {
$file = $_FILES['excel_file'];
if ($file['error'] === UPLOAD_ERR_OK) {
$allowedExt = ['xls', 'xlsx'];
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
if (in_array(strtolower($ext), $allowedExt)) {
// Сохраняем загруженный файл в временную директорию
$uploadFilePath = sys_get_temp_dir() . '/' . uniqid('upload_', true) . '.' . $ext;
if (move_uploaded_file($file['tmp_name'], $uploadFilePath)) {
try {
$htmlTable = excelToHtmlTable($uploadFilePath);
} catch (Exception $e) {
$error = 'Ошибка при обработке файла: ' . $e->getMessage();
}
// Удаляем временный файл
unlink($uploadFilePath);
} else {
$error = 'Не удалось сохранить загруженный файл.';
}
} else {
$error = 'Используйте файл только формата XLS или XLSX.';
}
} else {
$error = 'Ошибка загрузки файла.';
}
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Конвертер Excel в HTML таблицу</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container my-4">
<h1>Конвертер Excel в HTML таблицу (Bootstrap)</h1>
<form method="post" enctype="multipart/form-data" class="mb-4">
<div class="mb-3">
<label for="excel_file" class="form-label">Выберите Excel файл (.xls, .xlsx):</label>
<input type="file" name="excel_file" id="excel_file" class="form-control" accept=".xls,.xlsx" required>
</div>
<button type="submit" class="btn btn-primary">Конвертировать</button>
</form>
<?php if ($error): ?>
<div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<?php if ($htmlTable): ?>
<div class="mt-4">
<?= $htmlTable ?>
</div>
<?php endif; ?>
</div>
</body>
</html>
.xls или .xlsx.Если нужна помощь с установкой Composer или иными деталями — спрашивайте!