使用 php 上传时将 excel 文件扩展名从 xls 更改为 xlsx


Change excel file extension from xls to xlsx while uploading with php

是否有可能,如果是,如何在上传时或将文件保存到服务器上之前更改Excel文件扩展名?我正在使用php和mysql。

谢谢

你可以做这样的事情。

move_uploaded_file($_FILES['file']['tmp_name'], upload_PATH.'/'.$_FILES['file']['name'].'x');

但这只会更改扩展名为 xlsx 的文件名。它实际上不会将文件转换为 xlsx 格式。

正如之前在不同的回复中提到的,更改扩展名实际上不会改变格式,将.xls文件作为.xlsx文件提供不是一个好主意,因为这只会让任何试图阅读它的人感到困惑。

您可以做的(忽略文件转换和验证的潜在问题)是将上传的文件读取到 PHPExcel (http://phpexcel.codeplex.com) 等库中,然后使用内置函数将其导出为.xlsx文件。示例如下:

// Create a reader to read .xls format
$reader = PHPExcel_IOFactory::createReader('Excel5');
// Read the .xls file from upload storage
$workbook = $reader->load($_FILES['file']['tmp_name']);
// Create a writer to output in .xlsx format
$writer = PHPExcel_IOFactory::createWriter($workbook, 'Excel2007');
// Save file to destination .xlsx path
$writer->save($destination_path);

请记住,尽管这可能非常有效,但转换可能会弄乱文件的内容。这可能不可取,因为转换可能会导致数据丢失、格式更改和各种怪异。