以下是我尝试使用php将文件(excel / csv)导入MYSQL数据库的代码。这仅导入扩展名为.xls但不包含.xlsx的文件 我可能知道代码的混乱,要么我们必须在代码中包含任何库,要么应该进行任何更改。
<!DOCTYPE html>
<?php
include 'connect.php';
include 'Excel/reader.php';
function uploadFile($fieldName, $fileType, $folderName, $name = "")
{
$flg = 0;
$MaxID = "";
$ext = "";
$uploadfile = "";
if (isset($fieldName) AND $fieldName['name'] != '')
{
$flg = 1;
$allowed_filetypes = $fileType;
$max_filesize = 1048576;
$filename = $fieldName['name'];
if ($name == "")
$MaxID = time() . time() . rand(1, 100);
else
$MaxID = $name;
$ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
if($ext==".xlsx")
$ext=".xlsx";
if (!in_array($ext, $allowed_filetypes))
echo "<h1>The file you attempted to upload is not allowed...</h1>";
else if (filesize($fieldName['tmp_name']) > $max_filesize)
echo "<h1>The file you attempted to upload is too large...</h1>";
else
{
$uploadfile = $folderName . "/" . $MaxID . $ext;
if (move_uploaded_file($fieldName['tmp_name'], $uploadfile) == FALSE)
{
echo "<h1>Error in Uploading File...</h1>";
$MaxID = "";
}
else
$MaxID = $MaxID . $ext;
}
}
return $MaxID;
}
if(isset($_POST['submit']))
{
if($_FILES['csvFile']['name']!="")
{
$fileName=uploadFile($_FILES['excelFile'],array(".csv"),"excel_file");
$row=0;
if(($handle = fopen("test.csv".$fileName , "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
//print_r($data);
$query="INSERT INTO dealer_tbl(firstname,lastname,email,phone)VALUES('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."')";
mysql_query($query);
}
fclose($handle);
}
}
else if($_FILES['excelFile']['name']!="")
{
$fileName=uploadFile($_FILES['excelFile'],array(".xls",".xlsx"),"excel_file");
$data = new Spreadsheet_Excel_Reader();
$data->read('excel_file/'.$fileName);
for($i=1;$i<=$data->sheets[0]['numRows'];$i++)
{ $title=$data->sheets[0]['cells'][$i][1];
$firstname=$data->sheets[0]['cells'][$i][2];
$lastname=$data->sheets[0]['cells'][$i][3];
$mobile=$data->sheets[0]['cells'][$i][4];
$phone=$data->sheets[0]['cells'][$i][5];
echo $firstname."','".$lastname."','".$mobile."','".$phone;
$query="INSERT INTO dealer_tbl(title,firstname,lastname,email,phone)VALUES('".$title."','".$firstname."','".$lastname."','".$mobile."','".$phone."')";
mysql_query($query);
}
}
}
if(isset($_POST['delete']))
{
mysql_query("DELETE FROM StudentData");
}
?>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<link rel="stylesheet" href="master_net_effect.css" type="text/css" media="screen">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-responsive.min.css">
<link rel="stylesheet" href="css/bootstrap-custom.css">
<!-- HTML5 Shim, for IE6-IE8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<![endif]-->
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-38395785-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<!-- Navbar
================================================== -->
<div id="header"> <a id="con_logo_link" href="http://s672.t.en25.com/e/er?s=672& lid=3261&elq=00000000000000000000000000000000" target="_blank"><!-- logo --></a></div>
<div id="wrap">
<div class="container">
<div class="row">
<div class="span6" id="form-login">
<form class="form-horizontal well" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="upload_excel" enctype="multipart/form-data">
<fieldset>
<legend>Import Dealers List</legend>
<div class="control-group">
<div class="control-label">
<label>Select CSV File</label>
</div>
<div class="controls">
<input type="file" name="csvFile" class="input-large">
</div>
</div>
or
<div class="control-group">
<div class="control-label">
<label>Select Excel File</label>
</div>
<div class="controls">
<input type="file" name="excelFile" class="input-large">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" id="submit" name="submit" data-loading-text="Loading...">Upload</button>
</div>
</div>
</fieldset>
</form>
</div>
<div class="span3 hidden-phone"></div>
</div>
<form name="del" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="control-group">
<div class="controls">
<button type="submit" id="delete" name="delete" data-loading-text="Loading...">Delete Data</button>
</div>
</div>
</form>
<table class="table table-bordered">
<tr>
<th>Title</th>
<th>First Name</th>
<th>Last Name</th>
<th>Mobile</th>
<th>Phone</th>
</tr>
<?php
$res=mysql_query("SELECT * FROM dealer_tbl");
while($row=mysql_fetch_array($res))
{
?>
<tr>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['lastname']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['phone']; ?>..
答案 0 :(得分:2)
Spreadsheet_Excel_Reader
类当然只读取XLS
个文件。
如果您想阅读XLSX
,请尝试PhpExcel。这个库非常强大。
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel/IOFactory.php';
$inputFileName = 'your_file_to_import.xlsx';
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch(Exception $e) {
die('Error loading file :' . $e->getMessage());
}
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
print_r($sheetData);
答案 1 :(得分:0)
你可以试试这个对我有用:https://github.com/abdo0147/x2m这可以读取你的xlsx文件并给你一个php文件,它会将exel数据插入mysql,并会给你一个文件来测试你的数据是否正确插入