PHP導(dǎo)入導(dǎo)出Excel代碼,php導(dǎo)入導(dǎo)出excel
Jun 13, 2016 am 08:58 AMPHP導(dǎo)入導(dǎo)出Excel代碼,php導(dǎo)入導(dǎo)出excel
一.導(dǎo)入
導(dǎo)入需要使用能讀取Excel的組件,網(wǎng)上也有比較好的組件,這里分享我使用的:下載? 提取碼:vxyn。(注意兩個(gè)文件有引用關(guān)系)
<?php //傳入要導(dǎo)入的Excel的文件名 function import_to_DB($filename) { require_once'reader.php'; $data = new Spreadsheet_Excel_Reader(); //創(chuàng)建讀取Excel的對(duì)象 $data->setOutputEncoding('utf-8'); //設(shè)置讀取Excel內(nèi)容后輸出的字符編碼 $data->read("data/Excel/{$filename}.xls"); $db = mysql_connect('localhost', '用戶名', '密碼') or die("Could not connect to database."); //連接數(shù)據(jù)庫(kù) mysql_query("set names 'uft8'"); //輸出中文 mysql_select_db('數(shù)據(jù)庫(kù)名'); //選擇數(shù)據(jù)庫(kù) error_reporting(E_ALL ^ E_NOTICE); for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) { echo $data->sheets[0]['cells'][$i][列數(shù)]; //這里可以把每一行相應(yīng)列的值插到數(shù)據(jù)庫(kù)中,如: /* $sql="insert "表名" values(對(duì)應(yīng)項(xiàng)...)"; mysql_query($sql); 可加上錯(cuò)誤判斷 */ } ?>
總之,能夠讀出表格中每一行中的相應(yīng)列$data->sheets[0][行][列]的值,插入操作就好辦了。
二.導(dǎo)出
導(dǎo)出可以利用MIME協(xié)議輕松導(dǎo)出表格文件,不用依賴任何組件。按如下格式設(shè)置header即可導(dǎo)出Excel,同時(shí)瀏覽器進(jìn)行下載
header('Content-type: text/html; charset=utf-8'); header("Content-type:application/vnd.ms-excel;charset=UTF-8"); //application/vnd.ms-excel指定輸出Excel格式 header("Content-Disposition:filename=表格文件名.xls"); //輸出的表格名稱
完整代碼如下:
<?php header('Content-type: text/html; charset=utf-8'); header("Content-type:application/vnd.ms-excel;charset=UTF-8"); header("Content-Disposition:filename=表格文件名.xls"); $conn = mysql_connect("localhost","root","數(shù)據(jù)庫(kù)密碼") or die("不能連接數(shù)據(jù)庫(kù)"); mysql_select_db("數(shù)據(jù)庫(kù)名", $conn); mysql_query("set names 'UTF-8'"); $sql="select * from 表名 where 條件"; $result=mysql_query($sql); echo "表頭1\t表頭2\t表頭3\n"; while($row=mysql_fetch_array($result)){ echo $row[0]."\t".$row[1]."\t".$row[2]."\n"; } ?>
這里其實(shí)\t就是換格,\n就是換行。在一個(gè)網(wǎng)頁(yè)中設(shè)置這個(gè)php文件的鏈接,當(dāng)點(diǎn)擊時(shí)瀏覽器會(huì)自動(dòng)把傳過(guò)來(lái)的流保存為Excel文件。
PHPExcel 是用來(lái)操作Office Excel 文檔的一個(gè)PHP類庫(kù),它基于微軟的OpenXML標(biāo)準(zhǔn)和PHP語(yǔ)言??梢允褂盟鼇?lái)讀取、寫入不同格式的電子表格
導(dǎo)出類
PHPExcel類導(dǎo)出excel,同時(shí)對(duì)PHPExcel做了些精簡(jiǎn)處理,基本上可以滿足數(shù)據(jù)導(dǎo)出excel的功能
代碼如下:
<?php //載入PHPExcel類 require './phpexcel/PHPExcel.php'; //創(chuàng)建一個(gè)excel對(duì)象實(shí)例 $objPHPExcel = new PHPExcel(); //設(shè)置文檔基本屬性 $objProps = $objPHPExcel->getProperties(); $objProps->setCreator("Lao Mao"); $objProps->setLastModifiedBy("Lao Mao"); $objProps->setTitle("Office XLS Test Document"); $objProps->setSubject("Office XLS Test Document, Demo"); $objProps->setDescription("Test document, generated by PHPExcel."); $objProps->setKeywords("office excel PHPExcel"); $objProps->setCategory("Test"); //設(shè)置當(dāng)前的sheet索引,用于后續(xù)的內(nèi)容操作。 //一般只有在使用多個(gè)sheet的時(shí)候才需要顯示調(diào)用。 //缺省情況下,PHPExcel會(huì)自動(dòng)創(chuàng)建第一個(gè)sheet被設(shè)置SheetIndex=0 $objPHPExcel->setActiveSheetIndex(0); //設(shè)置當(dāng)前活動(dòng)sheet的名稱 $objActSheet = $objPHPExcel->getActiveSheet(); $objActSheet->setTitle('測(cè)試Sheet'); //設(shè)置單元格內(nèi)容www.jb51.net //這里的數(shù)據(jù)可以從數(shù)據(jù)庫(kù)中讀取,然后再做循環(huán)處理 $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'a1'); $objPHPExcel->getActiveSheet()->SetCellValue('A2', 'a2'); $objPHPExcel->getActiveSheet()->SetCellValue('A3', 'a3'); $objPHPExcel->getActiveSheet()->SetCellValue('A4', 'a4'); $objPHPExcel->getActiveSheet()->SetCellValue('A5', 'a5'); $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'b1'); $objPHPExcel->getActiveSheet()->SetCellValue('B2', 'b2'); $objPHPExcel->getActiveSheet()->SetCellValue('B3', 'b3'); $objPHPExcel->getActiveSheet()->SetCellValue('B4', 'b4'); $objPHPExcel->getActiveSheet()->SetCellValue('B5', 'b5'); $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'c1'); $objPHPExcel->getActiveSheet()->SetCellValue('C2', 'c2'); $objPHPExcel->getActiveSheet()->SetCellValue('C3', 'c3'); $objPHPExcel->getActiveSheet()->SetCellValue('C4', 'c4'); $objPHPExcel->getActiveSheet()->SetCellValue('C5', 'c5'); //輸出文檔 $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel); //設(shè)置header頭部信息,并輸出到瀏覽器 //header('Content-Type: application/vnd.ms-excel'); //header("Content-Disposition:attachment; filename=demo.xls"); //header('Cache-Control: max-age=0'); //$objWriter->save('php://output'); //保存至某一位置 $objWriter->save(dirname(__FILE__) . '/demo.xls');
導(dǎo)入excel的方法:
代碼:
<?php //載入PHPExcel類 include(dirname(__FILE__).'/phpexcel/PHPExcel.php'); $Obj = new PHPExcel_Reader_Excel5(); $Obj->setReadDataOnly(true); //讀取demo.xls文件 $phpExcel = $Obj->load(dirname(__FILE__).'/output.xls'); //獲取當(dāng)前活動(dòng)sheet $objWorksheet = $phpExcel->getActiveSheet(); //獲取行數(shù) $highestRow = $objWorksheet->getHighestRow(); //獲取列數(shù) $highestColumn = $objWorksheet->getHighestColumn(); $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); //循環(huán)輸出數(shù)據(jù) www.jb51.net $data = array(); for($row = 1; $row <= $highestRow; ++$row) { for($col = 0; $col < $highestColumnIndex; ++$col) { $val = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue(); $data[$row][$col] = trim($val); } } echo '<pre class="brush:php;toolbar:false">'; print_r($data); echo '';
但是這種方式有缺陷,老版本的excel有個(gè)數(shù)據(jù)上限,最多65536行數(shù)據(jù),這時(shí)我們就無(wú)法通過(guò)excel來(lái)實(shí)現(xiàn)大數(shù)據(jù)的導(dǎo)出, 但我估計(jì)也沒(méi)幾個(gè)有這么我數(shù)據(jù)吧,當(dāng)然如果有可以考慮使用csv來(lái)操作
以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach
