Home Backend Development PHP Tutorial How to import and export Excel files with PHP_PHP tutorial

How to import and export Excel files with PHP_PHP tutorial

Jul 13, 2016 am 10:43 AM
excel php under introduce exist Example import Export I operate document method of

Let me introduce to you two examples of operating excel in PHP. One is to use PHP-ExcelReader to import excel and output it, and the other is to directly input excel and export it. Let's see the examples below.


With the help of the PHP-ExcelReader open source class, we can easily import Excel file data. The sample code is as follows:

PHP-ExcelReader download address: http://sourceforge.net/projects/phpexcelreader/

Example. Import Excel file

The code is as follows Copy code
 代码如下 复制代码

require_once 'Excel/reader.php';
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('gbk');
$data->read('test.xls');
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
    for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
        echo """.$data->sheets[0]['cells'][$i][$j]."",";
    }
    echo "n";
}
?>

require_once 'Excel/reader.php'; $data = new Spreadsheet_Excel_Reader(); $data->setOutputEncoding('gbk'); $data->read('test.xls');

for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {

for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
 代码如下 复制代码

require_once 'reader.php';

// ExcelFile($filename, $encoding);
$data = new Spreadsheet_Excel_Reader();

// Set output Encoding.
$data->setOutputEncoding('gbk');

//”data.xls”是指要导入到mysql中的excel文件
$data->read('data.xls');

@ $db = mysql_connect('localhost', 'root', '123456') or
       die("Could not connect to database.");//连接数据库
mysql_query("set names 'gbk'");//输出中文
mysql_select_db('mydb');       //选择数据库
error_reporting(E_ALL ^ E_NOTICE);

for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
//以下注释的for循环打印excel表数据
/*
for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
            echo """.$data->sheets[0]['cells'][$i][$j]."",";
           }
           echo "n";
//PHP开源代码


*/
//以下代码是将excel表数据【3个字段】插入到mysql中,根据你的excel表字段的多少,改写以下代码吧!
    $sql = "INSERT INTO test VALUES('".
               $data->sheets[0]['cells'][$i][1]."','".
                 $data->sheets[0]['cells'][$i][2]."','".
                 $data->sheets[0]['cells'][$i][3]."')";
    echo $sql.'
';
       $res = mysql_query($sql);
}

?>

            echo """.$data->sheets[0]['cells'][$i][$j]."","; } echo "n"; } ?>
Example.phpexcel to excel 1. test.php
The code is as follows Copy code
require_once 'reader.php'; // ExcelFile($filename, $encoding); $data = new Spreadsheet_Excel_Reader(); // Set output Encoding. $data->setOutputEncoding('gbk'); //"data.xls" refers to the excel file to be imported into mysql $data->read('data.xls'); @ $db = mysql_connect('localhost', 'root', '123456') or          die("Could not connect to database.");//Connect to the database mysql_query("set names 'gbk'");//Output Chinese mysql_select_db('mydb'); //Select database error_reporting(E_ALL ^ ​​E_NOTICE); for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) { //The following commented for loop prints excel table data /* for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {                   echo """.$data->sheets[0]['cells'][$i][$j]."",";            } echo "n"; //PHP open source code */ //The following code inserts excel table data [3 fields] into mysql. Rewrite the following code according to the number of fields in your excel table! $sql = "INSERT INTO test VALUES('".                    $data->sheets[0]['cells'][$i][1]."','".                        $data->sheets[0]['cells'][$i][2]."','". $data->sheets[0]['cells'][$i][3]."')"; echo $sql.' ';          $res = mysql_query($sql); } ?>

Example. Export excel file


For example, if I need a program to export Excel from PHP, I only need to export the relevant data to the Excel table. Such a simple operation does not require the use of those class libraries. Just use the header method directly: header("Content-type:application/vnd.ms-excel");

Look at the code:

$head="Number".$tab."Remarks".$br; //The output content is as follows:
The code is as follows
 代码如下 复制代码

header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=Export_test.xls");
$tab="t"; $br="n";
$head="编号".$tab."备注".$br;
//输出内容如下:
echo $head.$br;
echo "test321318312".$tab;
echo "string1";
echo $br;

echo "330181199006061234".$tab; //直接输出会被Excel识别为数字类型
echo "number";
echo $br;

echo "="330181199006061234"".$tab; //原样输出需要处理
echo "string2";
echo $br;
?>

Copy code


header("Content-type:application/vnd.ms-excel");

header("Content-Disposition:attachment;filename=Export_test.xls");
代码如下 复制代码

header("Content-Type: application/msword");
header("Content-Disposition: attachment; filename=doc.doc");

$tab="t"; $br="n";
echo $head.$br;

echo "test321318312".$tab;

echo "string1";

echo $br;echo "330181199006061234".$tab; //Direct output will be recognized by Excel as a numeric type echo "number"; echo $br; echo "="330181199006061234"".$tab; //The original output needs to be processed echo "string2"; echo $br; ?> A problem will be found after exporting. If the data is numeric, some unexpected situations will occur. For example, "012345" will become "12345" in Excel; if you enter a long number such as an ID number, it will be expressed in scientific notation in Excel, and the last four digits will be deviated and changed to 0000 etc. This requires setting the cell to text format by echo "="330181199006061234""If the program is encoded in UTF-8, you need to use the iconv function to transcode it, otherwise it will be garbled and garbled.
The other word format import is similar, just specify the header:
The code is as follows Copy code
header("Content-Type: application/msword"); header("Content-Disposition: attachment; filename=doc.doc"); http://www.bkjia.com/PHPjc/633143.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/633143.htmlTechArticleLet me introduce to you two examples of operating excel in php. One is to use PHP-ExcelReader to import excel and Output, the other is to directly input into excel and export, see the example below. With...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Services CakePHP Services Sep 10, 2024 pm 05:26 PM

This chapter deals with the information about the authentication process available in CakePHP.

See all articles