search
HomeBackend DevelopmentPHP TutorialPHP# Some strategies for exporting data to Excel

PHP#dataExcelSome strategies for exporting

Export is actually more common in any type of back-end system. Under normal circumstances, the data exported by excel should be used more Make backups and drafts. Ideally, any business operation on business data should not rely on exporting data from the back-end business system and then manually interfering with it, but the reality is very skinny. . .

Functions such as data export need to be encapsulated if possible. There is only one data export, and its value will truly be reflected in subsequent adjustments and changes to business rules. When a typical application system has various data export requirements, it means that the business analysis of this application system is not good enough or very poor. When users only want to use the application system to export data to assist their business processes, the most terrifying situation is The distance between the user and the database will be just an export button. . .

Environment

1.PHP5.5.14 (cli) (built: Sep 9 201419:09:25)

2.PHP Excel 1.7.8 (http://www.codeplex.com/PHPExcel)

Processing logic

In fact, the key point of this type of problem is how to define the export rules. Whether this set of rules can adapt to business processes, the most basic way is to abstract the data export process into 3 basic stages, and then each stage can be gradually refined:

1. Definition of export rules

2.Adaptation of business data and export rules

3.Export rule analysis structureExcel

Example

This example implements the basic export function. There is no encapsulation, no focus on performance or other scalability issues.

<?php namespace org\ybygjy\comp\excel;

/**
 * Excel组件封装
 * <p>1.统一处理工程中针对excel的数据导出
 * @author WangYanCheng
 * @version 2015-1-22
 */
class ExcelComp {
	/**
	 * 构造函数
	 */
	public function __construct() {
		require_once 'org/ybygjy/library/excel/PHPExcel.php';
	}
	/**
	 * 测试入口
	 */
	public function doTest() {
		//构造原始数据
		$dataArray = $this->buildData();
		//导出
		$this->doExportData($dataArray);
	}
	/**
	 * 解析传递的原始数据并导出
	 * @param $dataArr
	 */
	public function doExportData($dataArr) {
		$phpObjExcel = new \PHPExcel();
		$worksSheet = $phpObjExcel->setActiveSheetIndex(0);
		//构造表头数据_Begin
		$tmpColTitles = [];
		$firstDataEntry = $dataArr[0];
		//分配列索引
		$colIndex = 0;
		foreach($firstDataEntry as $key => $val) {
			if (preg_match('/^_/', $key)) {
				continue;
			}
			if (is_array($val)) {
				//取array下的列名称
				$val = $val[0];
				$rowNums = count($val);
				foreach ($val as $innerKey => $innerValue) {
					$tmpColTitles[] = array(
						'parentKey' => $key,
						'key' => $innerKey,
						'colIndex' => $colIndex
					);
					$colIndex++;
				}
			} else {
				$tmpColTitles[] = array(
					'key'=>$key,
					'colIndex'=>$colIndex
				);
				$colIndex++;
			}
		}
		for($i = 0; $i setCellValueByColumnAndRow($colIndex,1,$key);	
		}
		//构造表头数据_End
		//填充单元格数据
		$currRow = 2;
		foreach ($dataArr as $dataEntry) {
			$mergeRow = $dataEntry['_DIMENSION'];
			foreach ($tmpColTitles as $colEntry) {
				$key = $colEntry['key'];
				$colIndex = $colEntry['colIndex'];
				$parentKey = (isset($colEntry['parentKey']) ? $colEntry['parentKey'] : null);
				if (empty($parentKey)) {
					$value = $dataEntry[$key];
					if ($mergeRow == 1) {
						$worksSheet->setCellValueByColumnAndRow($colIndex, $currRow, $value);
					} else {
						$worksSheet->mergeCellsByColumnAndRow($colIndex, $currRow, $colIndex, ($currRow + $mergeRow - 1))->setCellValueByColumnAndRow($colIndex, $currRow, $value);
					}
				} else {
					$tmpDataArr = $dataEntry[$parentKey];
					$innerRow = $currRow;
					for($index = 0; $index setCellValueByColumnAndRow($colIndex, $innerRow, $value);
						$innerRow++;
					}
				}
			}
			$currRow += $mergeRow;
		}
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Type: application/force-download');
		header('Content-Type: application/octet-stream');
		header('Content-Type: application/download');
		header('Content-Disposition: attachment;filename="HelloWord.xls"');
		header('Cache-Control: max-age=0');
		header('Cache-Control: max-age=1');
		header('Cache-Control: no-cache, must-revalidate');
		header('Pragma: public');
		$objWriter = \PHPExcel_IOFactory::createWriter($phpObjExcel, 'Excel5');
		$objWriter->save('php://output');
	}
	/**
	 * 构造测试数据
	 * @return multitype:multitype:string number multitype:multitype:string
	 */
	private function buildData() {
		$rtnData = array(
			array(
				'name'=>'YanCheng_01',
				'age'=>'20',
				'addr'=>array(
					array(
						'country'=>'China',
						'province'=>'ShanDong'
					),
					array(
						'country'=>'China',
						'province'=>'BeiJing'
					)
				),
				'_DIMENSION'=>2
			),
			array(
				'name'=>'YanCheng_02',
				'age'=>'21',
				'addr'=>array(
					array(
						'country'=>'China',
						'province'=>'LanZhou'
					),
					array(
						'country'=>'China',
						'province'=>'NingXia'
					)
				),
				'_DIMENSION'=>2
			),
			array(
				'name'=>'YanCheng_03',
				'age'=>'22',
				'addr'=>array(
					array(
						'country'=>'China',
						'province'=>'JiaYuGuan'
					)
				),
				'_DIMENSION'=>1
			)
		);
		return $rtnData;
	}
}

The above introduces some strategies for PHP# data Excel export, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
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
华为GT3 Pro和GT4的差异是什么?华为GT3 Pro和GT4的差异是什么?Dec 29, 2023 pm 02:27 PM

许多用户在选择智能手表的时候都会选择的华为的品牌,其中华为GT3pro和GT4都是非常热门的选择,不少用户都很好奇华为GT3pro和GT4有什么区别,下面就就给大家介绍一下二者。华为GT3pro和GT4有什么区别一、外观GT4:46mm和41mm,材质是玻璃表镜+不锈钢机身+高分纤维后壳。GT3pro:46.6mm和42.9mm,材质是蓝宝石玻璃表镜+钛金属机身/陶瓷机身+陶瓷后壳二、健康GT4:采用最新的华为Truseen5.5+算法,结果会更加的精准。GT3pro:多了ECG心电图和血管及安

实用Excel技巧分享:计算年数差、月数差、周数差实用Excel技巧分享:计算年数差、月数差、周数差Apr 22, 2022 am 09:56 AM

在之前的文章《实用Excel技巧分享:利用 数据透视表 来汇总业绩》中,我们学习了下Excel数据透视表,了解了利用数据透视表来汇总业绩的方法。而今天我们来聊聊怎么计算时间差(年数差、月数差、周数差),希望对大家有所帮助!

修复:截图工具在 Windows 11 中不起作用修复:截图工具在 Windows 11 中不起作用Aug 24, 2023 am 09:48 AM

为什么截图工具在Windows11上不起作用了解问题的根本原因有助于找到正确的解决方案。以下是截图工具可能无法正常工作的主要原因:对焦助手已打开:这可以防止截图工具打开。应用程序损坏:如果截图工具在启动时崩溃,则可能已损坏。过时的图形驱动程序:不兼容的驱动程序可能会干扰截图工具。来自其他应用程序的干扰:其他正在运行的应用程序可能与截图工具冲突。证书已过期:升级过程中的错误可能会导致此issu简单的解决方案这些适合大多数用户,不需要任何特殊的技术知识。1.更新窗口和Microsoft应用商店应用程

Word与Excel联动:表格借用Word进行分栏打印!Word与Excel联动:表格借用Word进行分栏打印!May 07, 2022 am 10:28 AM

在之前的文章《实用Word技巧分享:聊聊你没用过的“行号”功能》中,我们了解了Word中你肯定没用过的"行号”功能。今天继续实用Word技巧分享,看看Excel表格怎么借用Word进行分栏打印,快来收藏使用吧!

图文详解Excel中XLOOKUP函数典型用法整理图文详解Excel中XLOOKUP函数典型用法整理Apr 21, 2022 am 11:46 AM

本篇文章给大家带来了关于Excel的相关知识,其中主要介绍了关于XLOOKUP函数的相关知识,包括了常规查询、逆向查询、返回多列、自动除错以及近似查找等内容,下面一起来看一下,希望对大家有帮助。

图文详解Excel的折线图图文详解Excel的折线图May 07, 2022 am 11:28 AM

本篇文章给大家带来了关于excel的相关知识,其中主要介绍了关于折线图的相关问题,下面就根据一些示例来看一下怎么去应用,希望对大家有帮助。

如何修复无法连接到iPhone上的App Store错误如何修复无法连接到iPhone上的App Store错误Jul 29, 2023 am 08:22 AM

第1部分:初始故障排除步骤检查苹果的系统状态:在深入研究复杂的解决方案之前,让我们从基础知识开始。问题可能不在于您的设备;苹果的服务器可能会关闭。访问Apple的系统状态页面,查看AppStore是否正常工作。如果有问题,您所能做的就是等待Apple修复它。检查您的互联网连接:确保您拥有稳定的互联网连接,因为“无法连接到AppStore”问题有时可归因于连接不良。尝试在Wi-Fi和移动数据之间切换或重置网络设置(“常规”>“重置”>“重置网络设置”>设置)。更新您的iOS版本:

使用C#中的Array.Sort函数对数组进行排序使用C#中的Array.Sort函数对数组进行排序Nov 18, 2023 am 10:37 AM

标题:C#中使用Array.Sort函数对数组进行排序的示例正文:在C#中,数组是一种常用的数据结构,经常需要对数组进行排序操作。C#提供了Array类,其中有Sort方法可以方便地对数组进行排序。本文将演示如何使用C#中的Array.Sort函数对数组进行排序,并提供具体的代码示例。首先,我们需要了解一下Array.Sort函数的基本用法。Array.So

See all articles

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft