以下是一个利用 JS 上传 Excel 表格的完整代码示例,包含样式、Ajax 上传和 PHP 后端接收处理数据:

HTML

<!DOCTYPE html>
<html>
<head>
	<title>Excel 上传示例</title>
	<style>
		body {
			font-family: Arial, sans-serif;
			margin: 20px;
		}
		input[type='file'] {
			padding: 10px;
			border: 1px solid #ccc;
			border-radius: 5px;
			font-size: 16px;
			margin-bottom: 20px;
		}
		#result {
			display: none;
			margin-top: 20px;
			padding: 20px;
			background-color: #f5f5f5;
			border: 1px solid #ccc;
			border-radius: 5px;
			overflow-x: auto;
		}
		table {
			border-collapse: collapse;
			width: 100%;
		}
		th, td {
			padding: 10px;
			border: 1px solid #ccc;
		}
		th {
			background-color: #f2f2f2;
			font-weight: bold;
		}
	</style>
</head>
<body>
	<h1>Excel 上传示例</h1>
	<form>
		<input type='file' id='file' name='file'>
		<button type='button' id='upload-btn'>上传</button>
	</form>
	<div id='result'></div>
	<script src='https://code.jquery.com/jquery-3.6.0.min.js'></script>
	<script src='upload.js'></script>
</body>
</html>

JavaScript

$(document).ready(function() {
	$('#upload-btn').click(function() {
		var file_data = $('#file').prop('files')[0];
		var form_data = new FormData();
		form_data.append('file', file_data);
		$.ajax({
			url: 'upload.php',
			dataType: 'json',
			cache: false,
			contentType: false,
			processData: false,
			data: form_data,
			type: 'post',
			beforeSend: function() {
				$('#result').hide();
				$('#upload-btn').prop('disabled', true);
			},
			success: function(response) {
				$('#upload-btn').prop('disabled', false);
				if (response.success) {
					displayTable(response.data);
				} else {
					alert(response.message);
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
				$('#upload-btn').prop('disabled', false);
				alert('上传失败:' + textStatus);
			}
		});
	});
});

function displayTable(data) {
	$('#result').empty();
	var table = $('<table>');
	var headers = Object.keys(data[0]);
	var headerRow = $('<tr>');
	for (var i = 0; i < headers.length; i++) {
		headerRow.append($('<th>').text(headers[i]));
	}
	table.append(headerRow);
	for (var i = 0; i < data.length; i++) {
		var row = $('<tr>');
		for (var j = 0; j < headers.length; j++) {
			row.append($('<td>').text(data[i][headers[j]]));
		}
		table.append(row);
	}
	$('#result').append(table);
	$('#result').show();
}

PHP

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
	$file = $_FILES['file'];
	if ($file['error'] !== UPLOAD_ERR_OK) {
		echo json_encode(['success' => false, 'message' => '上传失败']);
		exit;
	}
	if ($file['type'] !== 'application/vnd.ms-excel' && $file['type'] !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
		echo json_encode(['success' => false, 'message' => '只能上传Excel文件']);
		exit;
	}
	$excel = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
	$spreadsheet = $excel->load($file['tmp_name']);
	$sheet = $spreadsheet->getActiveSheet();
	$data = [];
	foreach ($sheet->getRowIterator() as $row) {
		$rowData = [];
		$cellIterator = $row->getCellIterator();
		$cellIterator->setIterateOnlyExistingCells(false);
		foreach ($cellIterator as $cell) {
			$rowData[$cell->getColumn()] = $cell->getValue();
		}
		if (!empty($rowData)) {
			$data[] = $rowData;
		}
	}
	echo json_encode(['success' => true, 'data' => $data]);
	exit;
}
echo json_encode(['success' => false, 'message' => '无效请求']);
	exit;

该示例使用 jQuery 进行 Ajax 上传,使用 PhpSpreadsheet 库读取 Excel 文件并将数据转换为 JSON 格式返回。在前端,上传按钮单击时读取文件并将其作为 FormData 发送到 PHP 脚本。上传前禁用按钮以防止用户重复上传。上传完成后,成功响应将显示 Excel 数据表格,失败响应将显示错误消息。

JS 上传 Excel 表格 - 完整代码示例 (含样式、Ajax 和 PHP 处理)

原文地址: https://www.cveoy.top/t/topic/oeqq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录