将Excel文件上传到数据库

将Excel文件上传到数据库

问题描述:

我一直在想,因为我可以从Excel导入数据到我的数据库,是否有可能上传Excel文件本身,并能够显示在您的网站?将Excel文件上传到数据库

+0

是的,它是可能的;你可以发布你的代码,你尝试过吗? –

+0

我还没试过这个,我试过的那个是导入数据。我目前正在寻找一些关于如何做到这一点的教程。 – keme

对于客户端网页端,使用html格式<input type="file">将excel文件从浏览器上传到PHP文件。

示例性上传-submit.html:

<form action="upload.php"> 
    <input type="file" name="excel-upload" /> 
    <input type="submit" /> 
</form> 

在你的PHP上传脚本,您将需要包括PHPExcel库(https://github.com/PHPOffice/PHPExcel)来读取和解析上传的Excel文件。您可以阅读马克·贝克对很好的例子,如何从Excel中读取并插入到数据库中:how to use phpexcel to read data and insert into database?

upload.php的例子:

// Include PHPExcel_IOFactory 
include 'PHPExcel/IOFactory.php'; 

// Move the uploaded file from temporary server directory into an 'uploads' directory 
$fileName = basename($_FILES["excel-upload"]["name"]); 
$uploadedExcelFullPath = __DIR__.'/uploads/'.$fileName; 
move_uploaded_file($_FILES['excel-upload']['tmp_name'],$uploadedExcelFullPath); 


// Read your Excel workbook 
try { 
    $inputFileType = PHPExcel_IOFactory::identify($uploadedExcelFullPath); 
    $objReader = PHPExcel_IOFactory::createReader($inputFileType); 
    $objPHPExcel = $objReader->load($uploadedExcelFullPath); 
} catch(Exception $e) { 
    die('Error loading file "'.pathinfo($uploadedExcelFullPath,PATHINFO_BASENAME).'": '.$e->getMessage()); 
} 

// Get worksheet dimensions 
$sheet = $objPHPExcel->getSheet(0); 
$highestRow = $sheet->getHighestRow(); 
$highestColumn = $sheet->getHighestColumn(); 

// Loop through each row of the worksheet in turn 
for ($row = 1; $row <= $highestRow; $row++){ 
    // Read a row of data into an array 
    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, 
            NULL, 
            TRUE, 
            FALSE); 

    // Insert row data array into your database here 

    // You can also format data into HTML table row format and echo out here 
    var_dump($rowData); 
} 
+0

我会尝试这一个 – keme

+0

它没有工作,这是一个长期的,有没有其他简单的方法来做到这一点,我的意思是上传csv文件iiself而不是数据。我试图上传一个CSV文件到数据库,然后显示在我的网页上,并使其可下载。 – keme