使用PHP导入Excel和导出数据为Excel文件
有时需要将Excel表格的数据导入到mysql数据库中,我们使用PHP的一个开源项目PHP-ExcelReader可以轻松实现Excel的导入。
1、导入XLS
PHP-ExcelReader这是一个开源的项目,主要是来解析excel的文件,您可以到 http://sourceforge.net/projects/phpexcelreader获取最新版的源码。下载之后解压,主要用到excel文件夹里面的两个文件reader.php和oleread.inc。
导入Xls处理流程:选择xls文件->上传xls文件到服务器->通过PHP-ExcelReader解析excel->批量入库。
include_once("excel/reader.php"); //引入PHP-ExcelReader$tmp = $_FILES['file']['tmp_name'];if (empty ($tmp)) { echo '请选择要导入的Excel文件!'; exit;} $save_path = "xls/";$file_name = $save_path.date('Ymdhis') . ".xls"; //上传后的文件保存路径和名称if (copy($tmp, $file_name)) { $xls = new Spreadsheet_Excel_Reader(); $xls->setOutputEncoding('utf-8'); //设置编码 $xls->read($file_name); //解析文件 for ($i=2; $i<=$xls->sheets[0]['numRows']; $i++) { $name = $xls->sheets[0]['cells'][$i][0]; $sex = $xls->sheets[0]['cells'][$i][1]; $age = $xls->sheets[0]['cells'][$i][2]; $data_values .= "('$name','$sex','$age'),"; } $data_values = substr($data_values,0,-1); //去掉最后一个逗号 $query = mysql_query("insert into student (name,sex,age) values $data_values");//批量插入数据表中 if($query){ echo '导入成功!'; }else{ echo '导入失败!'; }}
PHP-ExcelReader读取上传的excel文件后,返回一个数组,里面包含了表格的所有信息,你可以循环获取需要的信息。
2、导出XLS
导出XLS流程:读取学生信息表->循环记录构建制表符分隔的字段信息->设置header信息->导出文件(下载)到本地
$result = mysql_query("select * from student");$str = "姓名\t性别\t年龄\t\n";$str = iconv('utf-8','gb2312',$str);while($row=mysql_fetch_array($result)){ $name = iconv('utf-8','gb2312',$row['name']); $sex = iconv('utf-8','gb2312',$row['sex']); $str .= $name."\t".$sex."\t".$row['age']."\t\n";}$filename = date('Ymd').'.xls';exportExcel($filename,$str);
exportExcel函数用于设置header信息。
function exportExcel($filename,$content){ header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/vnd.ms-execl"); header("Content-Type: application/force-download"); header("Content-Type: application/download"); header("Content-Disposition: attachment; filename=".$filename); header("Content-Transfer-Encoding: binary"); header("Pragma: no-cache"); header("Expires: 0"); echo $content;}
此外,关于导入和导出Excel,还可以使用PHPExcel,这个非常强大,大家有空可以去研究,官方网站: http://www.codeplex.com/PHPExcel 导入导出都成,可以导出office2007格式,同时兼容2003

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:
