首页 > 后端开发 > 正文

用PHP读取Excel、CSV文件(PhpOffice/PhpSpreadsheet读取和写入Excel)

2024-11-26 05:54:24 | 我爱编程网

今天我爱编程网小编整理了用PHP读取Excel、CSV文件(PhpOffice/PhpSpreadsheet读取和写入Excel)相关信息,希望在这方面能够更好的大家。

本文目录一览:

用PHP读取Excel、CSV文件(PhpOffice/PhpSpreadsheet读取和写入Excel)

用PHP读取Excel、CSV文件

PHP读取excel、csv文件的库有多个选择,其中使用较多的是PHPOffice/PHPExcel和PHPOffice/PhpSpreadsheet。尽管PHPExcel在2017年12月25日停止维护,但建议转向使用更新的PhpSpreadsheet。本篇文章将介绍如何在PHP中利用PhpSpreadsheet读取excel文件。

PhpSpreadsheet是一个纯PHP编写的库,提供丰富的类和方法,支持多种文件格式,包括xlsx、csv等。

要开始使用,首先需要配置环境和安装所需工具。使用Composer安装最新版本的PhpSpreadsheet(默认为1.5版本)。如果需要安装开发版本,可执行特定命令。

建立项目后,创建一个html文件用于上传Excel文件。确保form表单的enctype属性为multipart/form-data。运行后,程序将接收文件并调用PhpSpreadsheet进行读取。

使用PhpSpreadsheet读取文件非常灵活。读取不同格式文件时,只需调用相应方法,如使用\PhpOffice\PhpSpreadsheet\Reader\Xlsx()处理xlsx文件,使用\PhpOffice\PhpSpreadsheet\Reader\Csv()处理csv文件。通过一个工厂类\PhpOffice\PhpSpreadsheet\IOFactory,可以实现对文件类型自动识别。

在读取Excel文件内容时,需要先引入autoload,然后创建一个Xlsx的reader,加载上传的文件。读取时,注意文件的格式和内容的读取方式,确保获取到正确的数据。例如,针对时间数据的特殊处理,以及只读模式下的数据显示。

使用时,还可以通过设置如setLoadSheetsOnly来选择读取特定的sheet,或者读取指定行和列的数据。另外,可以列出所有sheet名称或单个sheet的信息,以满足更通用的使用需求。

总的来说,使用PhpSpreadsheet处理Excel和CSV文件非常高效且功能强大,几乎可以满足日常需求,是PHP开发中处理此类文件的理想选择。

用PHP读取Excel、CSV文件(PhpOffice/PhpSpreadsheet读取和写入Excel)

PhpOffice/PhpSpreadsheet读取和写入Excel

读取Excel文件,并将数据读取成数组$spreadsheet=\PhpOffice\PhpSpreadsheet\IOFactory::load($file['tmp_file']);//指定第一个工作表为当前$data=$spreadsheet->getSheet(0)->toArray();

PhpSpreadsheet是一个纯PHP编写的组件库,它使用现代PHP写法,代码质量和性能比PHPExcel高不少,完全可以替代PHPExcel(PHPExcel已不再维护)。使用PhpSpreadsheet可以轻松读取和写入Excel文档,支持Excel的所有操作。

官网:

1. 初识PhpSpreadsheet软件依赖

要使用PhpSpreadsheet需要满足以下条件:

PHP5.6或更改版本,推荐PHP7

支持php_zip扩展

支持php_xml扩展

支持php_gd2扩展

安装

现在开始,创建项目目录/PHPExcel,进入项目目录。

使用composer安装:

composerrequirephpoffice/phpspreadsheet 使用

在项目目录下新建/public目录,在public目录下创建示例文件test.php,编辑test.php,用以下代码。 我爱编程网

<?phprequire'../vendor/autoload.php';usePhpOffice\PhpSpreadsheet\Spreadsheet;usePhpOffice\PhpSpreadsheet\Writer\Xlsx;$spreadsheet=newSpreadsheet();$sheet=$spreadsheet->getActiveSheet();$sheet->setCellValue('A1','WelcometoHelloweba.');$writer=newXlsx($spreadsheet);$writer->save('hello.xlsx');

运行代码,你会发现在目录下生成一个hello.xlsx文件,打开Excel文件,你会看到Excel中的单元格A1中有“Welcome to Helloweba.”内容。当然你可以对单元格样式诸如颜色、背景、宽度、字体等等进行设置,这些会在接下来的几节中讲到。

PhpSpreadsheet特性

支持读取.xls,.xlsx,.html,.csv等格式文件,支持写入导出.xls,.xlsx,.html,.csv,.pdf格式文件。

提供丰富的API,提供单元格样式设置、Excel表格属性设置、图表设置等等诸多功能。使用PhpSpreadsheet完全可以生成一个外观结构都满足你的Excel表格文件。

卓越的性能,尤其在PHP7上表现优异,比PHPExcel强大很多。

2. 使用PhpSpreadsheet将Excel导入到MySQL数据库导入Excel

思路:使用PhpSpreadsheet读取Excel表格中的有用信息,然后组装成sql语句,最后批量插入到MySQL表中。

require'vendor/autoload.php';include('conn.php');//连接数据库$reader=\PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');$reader->setReadDataOnly(TRUE);$spreadsheet=$reader->load('students.xlsx');//载入excel表格$worksheet=$spreadsheet->getActiveSheet();$highestRow=$worksheet->getHighestRow();//总行数$highestColumn=$worksheet->getHighestColumn();//总列数$highestColumnIndex=\PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);//e.g.5$lines=$highestRow-2;if($lines<=0){exit('Excel表格中没有数据');}$sql="INSERTINTO`t_student`(`name`,`chinese`,`maths`,`english`)VALUES";for($row=3;$row<=$highestRow;++$row){$name=$worksheet->getCellByColumnAndRow(1,$row)->getValue();//姓名$chinese=$worksheet->getCellByColumnAndRow(2,$row)->getValue();//语文$maths=$worksheet->getCellByColumnAndRow(3,$row)->getValue();//数学$english=$worksheet->getCellByColumnAndRow(4,$row)->getValue();//外语$sql.="('$name','$chinese','$maths','$english'),";}$sql=rtrim($sql,",");//去掉最后一个,号try{$db->query($sql);echo'OK';}catch(Exception$e){echo$e->getMessage();}

worksheet->getCellByColumnAndRow(col, row)->getValue() 可以获取表格中任意单元格数据内容,col表示单元格所在的列,以数字表示,A列表示第一列,$row表示所在的行。

3. 使用PhpSpreadsheet将数据导出为Excel文件一、设置表头

首先我们引入自动加载PhpSpreadsheet库,然后实例化,设置工作表标题名称为:学生成绩表,接着设置表头内容。表头分为两行,第一行是表格的名称,第二行数表格列名称。最后我们将第一行单元格进行合并,并设置表头内容样式:字体、对齐方式等。

require'vendor/autoload.php';usePhpOffice\PhpSpreadsheet\Spreadsheet;usePhpOffice\PhpSpreadsheet\Writer\Xlsx;include('conn.php');//连接数据库$spreadsheet=newSpreadsheet();$worksheet=$spreadsheet->getActiveSheet();//设置工作表标题名称$worksheet->setTitle('学生成绩表');//表头//设置单元格内容$worksheet->setCellValueByColumnAndRow(1,1,'学生成绩表');$worksheet->setCellValueByColumnAndRow(1,2,'姓名');$worksheet->setCellValueByColumnAndRow(2,2,'语文');$worksheet->setCellValueByColumnAndRow(3,2,'数学');$worksheet->setCellValueByColumnAndRow(4,2,'外语');$worksheet->setCellValueByColumnAndRow(5,2,'总分');//合并单元格$worksheet->mergeCells('A1:E1');$styleArray=['font'=>['bold'=>true],'alignment'=>['horizontal'=>\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,],];//设置单元格样式$worksheet->getStyle('A1')->applyFromArray($styleArray)->getFont()->setSize(28);$worksheet->getStyle('A2:E2')->applyFromArray($styleArray)->getFont()->setSize(14); 二、读取数据

我们连接数据库后,直接读取学生成绩表t_student,然后for循环,设置每个单元格对应的内容,计算总成绩。注意的是表格中的数据是从第3行开始,因为第1,2行是表头占用了。

然后,我们设置整个表格样式,给表格加上边框,并且居中对齐。

$sql="SELECTid,name,chinese,maths,englishFROM`t_student`";$stmt=$db->query($sql);$rows=$stmt->fetchAll(PDO::FETCH_ASSOC);$len=count($rows);$j=0;for($i=0;$i<$len;$i++){$j=$i+3;//从表格第3行开始$worksheet->setCellValueByColumnAndRow(1,$j,$rows[$i]['name']);$worksheet->setCellValueByColumnAndRow(2,$j,$rows[$i]['chinese']);$worksheet->setCellValueByColumnAndRow(3,$j,$rows[$i]['maths']);$worksheet->setCellValueByColumnAndRow(4,$j,$rows[$i]['english']);$worksheet->setCellValueByColumnAndRow(5,$j,$rows[$i]['chinese']+$rows[$i]['maths']+$rows[$i]['english']);}$styleArrayBody=['borders'=>['allBorders'=>['borderStyle'=>\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,'color'=>['argb'=>'666666'],],],'alignment'=>['horizontal'=>\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,],];$total_rows=$len+2;//添加所有边框/居中$worksheet->getStyle('A1:E'.$total_rows)->applyFromArray($styleArrayBody); 三、下载保存

强制浏览器下载数据并保存为Excel文件

$filename='成绩表.xlsx';header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');header('Content-Disposition:attachment;filename="'.$filename.'"');header('Cache-Control:max-age=0');$writer=\PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet,'Xlsx');$writer->save('php://output');

如想要保存为.xls文件格式的话,可以改下header代码:

$filename='成绩表.xlsx';header('Content-Type:application/vnd.ms-excel');header('Content-Disposition:attachment;filename="'.$filename.'"');header('Cache-Control:max-age=0');$writer=\PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet,'xls');$writer->save('php://output'); 4. 详解PhpSpreadsheet设置单元格

PhpSpreadsheet提供了丰富的API接口,可以设置诸多单元格以及文档属性,包括样式、图片、日期、函数等等诸多应用,总之你想要什么样的Excel表格,PhpSpreadsheet都能做到。

引入了正确的文件并实例化:usePhpOffice\PhpSpreadsheet\Spreadsheet;$spreadsheet=newSpreadsheet();$worksheet=$spreadsheet->getActiveSheet(); 字体

第1行代码将A7至B7两单元格设置为粗体字,Arial字体,10号字;第2行代码将B1单元格设置为粗体字。

$spreadsheet->getActiveSheet()->getStyle('A7:B7')->getFont()->setBold(true)->setName('Arial')->setSize(10);;$spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setBold(true); 颜色

将文字颜色设置为红色

composerrequirephpoffice/phpspreadsheet0 图片

可以将图片加载到Excel中

composerrequirephpoffice/phpspreadsheet1 列宽

将A列宽度设置为30(字符):

composerrequirephpoffice/phpspreadsheet2

如果需要自动计算列宽,可以这样:

composerrequirephpoffice/phpspreadsheet3

设置默认列宽为12:

composerrequirephpoffice/phpspreadsheet4 行高

设置第10行行高为100pt:

composerrequirephpoffice/phpspreadsheet5

设置默认行高:

composerrequirephpoffice/phpspreadsheet6 对齐

将A1单元格设置为水平居中对齐:

composerrequirephpoffice/phpspreadsheet7 合并

将A18到E22合并为一个单元格:

composerrequirephpoffice/phpspreadsheet8 拆分

将合并后的单元格拆分:

composerrequirephpoffice/phpspreadsheet9 边框

将B2至G8的区域添加红色边框:

<?phprequire'../vendor/autoload.php';usePhpOffice\PhpSpreadsheet\Spreadsheet;usePhpOffice\PhpSpreadsheet\Writer\Xlsx;$spreadsheet=newSpreadsheet();$sheet=$spreadsheet->getActiveSheet();$sheet->setCellValue('A1','WelcometoHelloweba.');$writer=newXlsx($spreadsheet);$writer->save('hello.xlsx');0 工作表标题

设置当前工作表标题:

<?phprequire'../vendor/autoload.php';usePhpOffice\PhpSpreadsheet\Spreadsheet;usePhpOffice\PhpSpreadsheet\Writer\Xlsx;$spreadsheet=newSpreadsheet();$sheet=$spreadsheet->getActiveSheet();$sheet->setCellValue('A1','WelcometoHelloweba.');$writer=newXlsx($spreadsheet);$writer->save('hello.xlsx');1 日期时间

设置日期格式:

<?phprequire'../vendor/autoload.php';usePhpOffice\PhpSpreadsheet\Spreadsheet;usePhpOffice\PhpSpreadsheet\Writer\Xlsx;$spreadsheet=newSpreadsheet();$sheet=$spreadsheet->getActiveSheet();$sheet->setCellValue('A1','WelcometoHelloweba.');$writer=newXlsx($spreadsheet);$writer->save('hello.xlsx');2 换行

使用\n进行单元格内换行,相当于(ALT+"Enter"):

<?phprequire'../vendor/autoload.php';usePhpOffice\PhpSpreadsheet\Spreadsheet;usePhpOffice\PhpSpreadsheet\Writer\Xlsx;$spreadsheet=newSpreadsheet();$sheet=$spreadsheet->getActiveSheet();$sheet->setCellValue('A1','WelcometoHelloweba.');$writer=newXlsx($spreadsheet);$writer->save('hello.xlsx');3 超链接

将单元格设置为超链接形式:

<?phprequire'../vendor/autoload.php';usePhpOffice\PhpSpreadsheet\Spreadsheet;usePhpOffice\PhpSpreadsheet\Writer\Xlsx;$spreadsheet=newSpreadsheet();$sheet=$spreadsheet->getActiveSheet();$sheet->setCellValue('A1','WelcometoHelloweba.');$writer=newXlsx($spreadsheet);$writer->save('hello.xlsx');4 使用函数

使用SUM计算B5到C5之间单元格的总和。其他函数同理:最大数(MAX),最小数(MIN),平均值(AVERAGE):

<?phprequire'../vendor/autoload.php';usePhpOffice\PhpSpreadsheet\Spreadsheet;usePhpOffice\PhpSpreadsheet\Writer\Xlsx;$spreadsheet=newSpreadsheet();$sheet=$spreadsheet->getActiveSheet();$sheet->setCellValue('A1','WelcometoHelloweba.');$writer=newXlsx($spreadsheet);$writer->save('hello.xlsx');5 设置文档属性

可以设置Excel文档属性:

<?phprequire'../vendor/autoload.php';usePhpOffice\PhpSpreadsheet\Spreadsheet;usePhpOffice\PhpSpreadsheet\Writer\Xlsx;$spreadsheet=newSpreadsheet();$sheet=$spreadsheet->getActiveSheet();$sheet->setCellValue('A1','WelcometoHelloweba.');$writer=newXlsx($spreadsheet)

thinkPHP怎样使用PHPExcel导出网站数据为excel

我爱编程网(https://www.52biancheng.com)小编还为大家带来thinkPHP怎样使用PHPExcel导出网站数据为excel的相关内容。

第一步:先去下载PHPExcel插件压缩包,解压后只用到Classes文件夹里面的文件就行。
第二步:然后把Classes文件夹名称改为PHPExcel (也可以不用改),再放在thinkPHP指定的第三方类库目录文件夹Vendor下面,第三方类库目录在ThinkPHP/Library 里面


第三步:整理数据,整理成适合excel表格式的数据,不多说直接给代码

public function export(){//导出Excel表数据整理
$xlsData  = M('table')->select();//查找需要导出的数据
        $xlsCell  = array(//设置excel文档的格式第一行就相当于标题
            array('id','ID号'),
            array('title','标题'),
            array('time','时间'),
            array('content','内容')
        );

$newArray = array();//自定义数组
        foreach ($xlsData as $k => $v)
        {//然后把所有查找到的数据根据设置第一行的标题相对应放进数组里面
$newArray[$k]['id'] = $v['id'];
                $newArray[$k]['title'] = $v['title'];
                $newArray[$k]['time'] = date('Y-m-d',$v['time']);
$newArray[$k]['content'] = $v['content'];
        }
        $xlsName = 'Excel表数据';//设置Excel表文件名称
        $this->exportExcel($xlsName,$xlsCell,$newArray);//调用PHPExcel插件,这步的函数也需要自定义
    }

/**
     * @param $xlsName 名称
     * @param $xlsCell 参数(标题数组)
     * @param $newArray 内容(数据数组)
     */
    public function exportExcel($xlsName,$xlsCell,$newArray){

        $xlsTitle = iconv('utf-8', 'gb2312', $xlsName);//文件名称需要转码避免乱码出错
        $xlsCell_num = count($xlsCell);
        $newArray_num = count($newArray);
        
        vendor("PHPExcel.PHPExcel");//关键,利用thinkphp内置函数嵌套PHPExcel插件,如果在第二步没有改文件夹名称就这样:vendor("Classes.PHPExcel");点之前表示插件文件夹,点之后的表示PHPExcel.php文件的名称不要后缀名
        $objPHPExcel = new \PHPExcel();//实例化PHPExcel
        
        $column_key = 'A';//excel表的每个单元格都是A1,A2,A3....类似的,大写字母代表列,数字代表行,那么第一行就是标题了
foreach($xlsCell as $k=>$v){
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($column.'1',$v);//有多少标题列先写进第一行
$column_key++;//这样循环的好处就是不用限定有多少列,可以根据你的数据表字段有多少就导出多少列
}
        for($i=0;$i<$newArray_num;$i++){//第一层循环表示多少行
            $column_key = 'A';
            for($j=0;$j<$xlsCell_num;$j++){//第二层表示列
                $objPHPExcel->getActiveSheet(0)->setCellValue($column_key.($i+2), $newArray[$i][$xlsCell[$j][0]]);//($i+2)表示从第二行开始,第一行已经设置为标题了
                $column_key++;
            }
        }
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$xlsTitle.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');//Excel5为xls格式,excel2007为xlsx格式
        $objWriter->save('php://output');
        exit;
    }

运行后的效果文件图

以上就是我爱编程网小编给大家带来的用PHP读取Excel、CSV文件(PhpOffice/PhpSpreadsheet读取和写入Excel)全部内容,希望对大家有所帮助!更多相关文章关注我爱编程网:www.52biancheng.com

免责声明:文章内容来自网络,如有侵权请及时联系删除。
标签: PHP
与“用PHP读取Excel、CSV文件(PhpOffice/PhpSpreadsheet读取和写入Excel)”相关推荐
php读取excel中的日期出错。 PhpOffice/PhpSpreadsheet读取和写入Excel
php读取excel中的日期出错。 PhpOffice/PhpSpreadsheet读取和写入Excel

php读取excel中的日期出错。1、工作簿处于“公式审核”状态,按ctrl+~切回到正常工作状态就可以。2、如果还不行,请在表格之外任意一处把单元格设置成日期格式,然后随便填一个日期,再用格式刷刷你表格中的日期方法:写入excel的时候在时间上加‘’,让他变成字符串,读取就没错了。excelTime的函数也可以正确转化时间error_reporting(E_ALL);

2025-02-17 12:21:38
Highcharts图表结构分析:详解坐标轴及其类型 PhpOffice/PhpSpreadsheet读取和写入Excel
Highcharts图表结构分析:详解坐标轴及其类型 PhpOffice/PhpSpreadsheet读取和写入Excel

Highcharts图表结构分析:详解坐标轴及其类型电脑软件名称:Highcharts大小:13MB版本:3.0.7类别:开发工具语言:英文应用平台:windows/Highcharts所有的图表除了饼图都有X轴和Y轴,默认情况下,x轴显示在图表的底部,y轴显示在左侧(多个y轴时可以是显示在左右两侧),通过chart.inverted=true可以让x,y轴显示位置对调

2025-02-10 08:15:07
PHP远程读取excel文件,怎么读取
PHP远程读取excel文件,怎么读取

PHP远程读取excel文件,怎么读取PHPExcel通过PHPExcel_Shared_OLERead类的read方法读取文件但read方法里使用了is_readable函数来确认文件是否存在,而is_readable不能作用于url所以不可直接远程读取但若绕过is_readable函数的话,就是可以的publicfunctionread($sFileName){/

2024-10-27 15:05:05
如何读取excel文件 php
如何读取excel文件 php

php怎样读取excel表格内容?常用的用PHP读取EXCEL的方法有以下三种,各自有各自的优缺点。个人推荐用第三种方法,因为它可以跨平台使用。\x0d\x0a\x0d\x0a1.以.csv格式读取\x0d\x0a\x0d\x0a将.xls转换成.csv的文本格式,然后再用PHP分析这个文件,和PHP分析文本没有什么区别。\x0d\x0a\x0d\x0a优点:跨平台,效率比较高、可以读写。\

2024-08-09 23:33:45
php读取excel怎么读取sheet2
php读取excel怎么读取sheet2

php读取excel怎么读取sheet2PHPEXCEL读取EXCEL时如何读取第二张表列号?$objPHPExcel=newPHPexcel();$objPHPExcel=$objReader-加载($sheet=$objPHPExcel-getactivesheet(1);这里的$sheet是sheet2的对象,然后就可以继续操作了。$cellarray=$s

2024-09-22 15:12:00
php文件读取函数 PHP中使用fgets函数读取文件内容
php文件读取函数 PHP中使用fgets函数读取文件内容

file_get_contents的用法file_get_contents的用法答案:file_get_contents是一个用于读取文件内容的PHP函数。它可以将文件的内容直接读取到一个字符串中,便于后续的处理和操作。使用此函数,你可以轻松地从本地文件系统或其他可访问的URL获取文件内容。详细解释:1.基本用法:file_g

2024-12-21 13:05:15
分享自用的php爬取网页,读取、写入txt语句! 通过php随机读取txt文件的某一行
分享自用的php爬取网页,读取、写入txt语句! 通过php随机读取txt文件的某一行

php读取txt,从新排版后生成新txt我发现你第一列内容长度不固定,可以这么写,已测直接用就行。&lt;?php    $fp = fopen('txt1.txt', 'r');    $new_txt = '';    while(! feof($fp)){        $num = fgets($fp);        $num_info = explode(',',$num)

2024-12-07 00:21:17
php用ODBC连接SQL SERVER出错!!!!(php怎样读取excel表格内容?)
php用ODBC连接SQL SERVER出错!!!!(php怎样读取excel表格内容?)

php用ODBC连接SQLSERVER出错!!!!还可能是这个原因,你的系统应该是64bit的,在新建dsn要用64bit的odbc,不能用WIN7自带控制面板里面的管理工具里面的数据源添加。必须用C:\Windows\SysWOW64\odbcad32.exe来添加数据源才好用。php怎样读取excel表格内容?常用的用PHP读取EXCEL的方法有以下三种,各自有各自的优缺点。个人推

2025-02-06 16:29:13