Table of Contents
Use PHPExcel to export data to excel file in xls format
Home Backend Development PHP Tutorial Use PHPExcel to export data to excel files in xls format_PHP tutorial

Use PHPExcel to export data to excel files in xls format_PHP tutorial

Jul 13, 2016 am 10:15 AM
data document Format

Use PHPExcel to export data to excel file in xls format

When developing a business license management system in a certain place, the data needs to be exported into an excel file. Although I used import and export once when I was doing the ERP of a certain group a year ago, I was too busy at that time to write a blog. Years have passed and I have almost forgotten about it, so I will take advantage of today to write this use in the blog as a reference for future development, so as not to need to export and find information when using it again, and also to give other colleagues a reference. Author: DragonDean, blog address: http://www.cnblogs.com/dragondean/
What is PHPExcel?
PHPExcel is a PHP class library used to operate Office Excel documents. It is based on Microsoft's OpenXML standard and PHP language. You can use it to read and write spreadsheets in different formats, such as Excel (BIFF) .xls, Excel 2007 (OfficeOpenXML) .xlsx, CSV, Libre/OpenOffice Calc .ods, Gnumeric, PDF, HTML, etc.
Download PHPExcel
The official website address of phpexcel is: http://phpexcel.codeplex.com/, from which we can download the required files. I downloaded version 1.8. After downloading, unzip it to the root directory of the website.
Development background description
This development uses the ThinkPHP framework to export all content based on the query conditions. There is also an import function, I will write another article about it. For more detailed instructions, please refer to the comments in the code section.
The code for the export part is as follows:
Copy code
//Import related files
require_once $_SERVER['DOCUMENT_ROOT'].'/PHPExcel/Classes/PHPExcel.php';
//Instantiation
$phpexcel = new PHPExcel();
//Set the ratio title
$phpexcel->getActiveSheet()->setTitle('Yichuang Technology prompts technical support');
//Set header
$phpexcel->getActiveSheet() ->setCellValue('A1','Meal Certificate Word')
-& gt; setcellvalue ('b1', 'unit name')
-& gt; setcellvalue ('c1', 'legal representative')
-& gt; setcellvalue ('d1', 'city')
-& gt; setcellvalue ('e1', 'region')
-& gt; setcellvalue ('f1', 'address')
-& gt; setcellvalue ('g1', 'category')
-& gt; setcellvalue ('h1', 'remark (business scope)'
-& gt; setcellValue ('i1', 'issuing authority')
-& gt; setcellvalue ('j1', 'start date')
-& gt; setcellvalue ('k1', 'end date')
-& gt; setcellvalue ('l1', 'food safety manager')
-& gt; setcellvalue ('m1', 'whether to proof')
-& gt; setcellValue ('n1', 'issuing certificate date')
-& gt; setcellvalue ('o1', 'contact number')
-& gt; setcellvalue ('p1', 'use area')
-& gt; setcellvalue ('q1', 'number of employees' "
-& gt; setcellvalue ('r1', 'change situation')
-& gt; setcellvalue ('s1', 'holding the certificate')
-& gt; setcellValue ('t1', '' belonging to the regulatory department ');
//Get the data that needs to be exported from the database
$list=$db->where($where)->select();
//Use foreach to start writing data from the second row, because the first row is the header
$i=2;
foreach($list as $val){
$phpexcel->getActiveSheet() ->setCellValue('A'.$i,'吉'.$val['czz_nian'].$val['czz_hao'])
-& gt; setcellvalue ('b'. $ I, $ value ['danwei'])
-& gt; setcellvalue ('c'. $ I, $ valr ['faren']
-& gt; setcellValue ('d'. $ I, $ value ['dz_chengshi'])
-& gt; setcellValue ('e'. $ I, $ value ['dz_diqu'])
-& gt; setcellValue ('f'. $ I, $ value ['dizhi'])
-& gt; setcellvalue ('g'. $ I, $ value ['leibie'])
-& gt; setcellvalue ('h'. $ I, $ value ['beizhu'])
-& gt; setcellValue ('I'. $ I, $ value ['fazheng'])
>
-& gt; setcellvalue ('k'. $ I, $ value ['zz_nian'].'- '. $ Val [' zz_yue '] .'-'. $ Val ['zz_ri'])
-& gt; setcellvalue ('l'. $ I, $ value ['anquan'])
-& gt; setcellvalue ('m'. $ I, $ value ['zhizheng']
                                                                                                                                                                                                              ->setCellValue('N'.$i, $val['fz_nian'].'-'.$val['fz_yue'].'-'.$val['fz_ri'])
-& gt; setcellValue ('o'. $ I, $ value ['dianhua'])
-& gt; setcellvalue ('p'. $ I, $ value ['shiyongmianji'])
-& gt; setcellvalue ('q'. $ I, $ value ['renshu']
-& gt; setcellValue ('r'. $ I, $ value ['biangngng'])
-& gt; setcellvalue ('s'. $ I, $ valr ['chizheng']
-& gt; setcellvalue ('t'. $ I, $ value ['keshi']);
$i++;
}
$obj_Writer = PHPExcel_IOFactory::createWriter($phpexcel,'Excel5');
$filename ='Export'. date('Y-m-d').".xls";//File name
//Set header
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream"); ​​
header("Content-Type: application/download");
header('Content-Disposition:inline;filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
$obj_Writer->save('php://output');//Output
die();//Planting execution
Copy code
Exported file preview:
Reference for other related attribute settings (from online information)
Copy code
//Set the basic properties of the document
$objProps = $phpexcel->getProperties();
$objProps->setCreator("Zhanggong District Medical Insurance Bureau");
$objProps->setLastModifiedBy("Zhanggong District Medical Insurance Bureau");
$objProps->setTitle("Monthly increase and decrease report for employees of Zhanggong District Medical Insurance Bureau");
$objProps->setSubject("Monthly increase and decrease report for employees of Zhanggong District Medical Insurance Bureau");
$objProps->setDescription("Monthly increase and decrease report for employees of Zhanggong District Medical Insurance Bureau");
$objProps->setKeywords("Monthly increase and decrease report for employees of Zhanggong District Medical Insurance Bureau");
$objProps->setCategory("Change Report");
Copy code
How to merge/separate cells in PHPExcel
$objPHPExcel->getActiveSheet()->mergeCells('A18:E22');
$objPHPExcel->getActiveSheet()->unmergeCells('A18:E22');
How to set column width/row height in PHPExcel
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
$objPHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(16);
How to set styles in PHPExcel
Copy code
$objStyleA1 = $phpexcel->getActiveSheet()->getStyle('A1');
$objStyleA1->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //Set the horizontal alignment
$objStyleA1->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER); //Set vertical alignment
$objFontA1 = $objStyleA1->getFont();
$objFontA1->setName('宋体');
$objFontA1->setSize(18); $objFontA1->setBold(true);
Copy code
How to set borders in PHPExcel
Copy code
$objActSheet->getStyle('A2')->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
$objActSheet->getStyle('A2')->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
$objActSheet->getStyle('A2')->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
$objActSheet->getStyle('A2')->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN );
$objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getLeft()->getColor()->setARGB('FF993300');// Set border color
Copy code
Please search Baidu for more information. If you have any questions, please correct me!

http://www.bkjia.com/PHPjc/905597.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/905597.htmlTechArticleUsing PHPExcel to export data to excel files in xls format is needed when developing a business license management system in a certain place Export the data into an excel file. Although I did the ER of a certain group a year ago...
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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 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)

Use ddrescue to recover data on Linux Use ddrescue to recover data on Linux Mar 20, 2024 pm 01:37 PM

DDREASE is a tool for recovering data from file or block devices such as hard drives, SSDs, RAM disks, CDs, DVDs and USB storage devices. It copies data from one block device to another, leaving corrupted data blocks behind and moving only good data blocks. ddreasue is a powerful recovery tool that is fully automated as it does not require any interference during recovery operations. Additionally, thanks to the ddasue map file, it can be stopped and resumed at any time. Other key features of DDREASE are as follows: It does not overwrite recovered data but fills the gaps in case of iterative recovery. However, it can be truncated if the tool is instructed to do so explicitly. Recover data from multiple files or blocks to a single

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Apr 03, 2024 pm 12:04 PM

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. Mar 21, 2024 pm 09:17 PM

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box "Error 0x80004005: Unspecified Error" will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? Mar 14, 2024 pm 02:07 PM

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Apr 01, 2024 pm 07:46 PM

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

What is hiberfil.sys file? Can hiberfil.sys be deleted? What is hiberfil.sys file? Can hiberfil.sys be deleted? Mar 15, 2024 am 09:49 AM

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks The vitality of super intelligence awakens! But with the arrival of self-updating AI, mothers no longer have to worry about data bottlenecks Apr 29, 2024 pm 06:55 PM

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

See all articles