1.PhpOffice/PhpSpreadsheet读取和写入Excel
2.åºäºphpä¸ä½¿ç¨excelçç®åä»ç»
3.php生成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文档,源码atomicboolean源码支持Excel的源码所有操作。
官网:poser安装:
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.”内容。当然你可以对单元格样式诸如颜色、背景、宽度、字体等等进行设置,net交友网站源码这些会在接下来的几节中讲到。
PhpSpreadsheet特性支持读取.xls,.xlsx,.html,.csv等格式文件,支持写入导出.xls,.xlsx,.html,.csv,卖qq号网站源码.pdf格式文件。
提供丰富的API,提供单元格样式设置、Excel表格属性设置、图表设置等等诸多功能。使用PhpSpreadsheet完全可以生成一个外观结构都满足你的Excel表格文件。
卓越的性能,尤其在PHP7上表现优异,比PHPExcel强大很多。winsock网络编程经络_源码
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文件一、linux stdarg.h源码设置表头首先我们引入自动加载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();$worksheet->getStyle('A2:E2')->applyFromArray($styleArray)->getFont()->setSize();二、读取数据我们连接数据库后,直接读取学生成绩表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'=>''],],],'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字体,号字;第2行代码将B1单元格设置为粗体字。
$spreadsheet->getActiveSheet()->getStyle('A7:B7')->getFont()->setBold(true)->setName('Arial')->setSize();;$spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);颜色将文字颜色设置为红色
composerrequirephpoffice/phpspreadsheet0可以将加载到Excel中
composerrequirephpoffice/phpspreadsheet1列宽将A列宽度设置为(字符):
composerrequirephpoffice/phpspreadsheet2如果需要自动计算列宽,可以这样:
composerrequirephpoffice/phpspreadsheet3设置默认列宽为:
composerrequirephpoffice/phpspreadsheet4行高设置第行行高为pt:
composerrequirephpoffice/phpspreadsheet5设置默认行高:
composerrequirephpoffice/phpspreadsheet6对齐将A1单元格设置为水平居中对齐:
composerrequirephpoffice/phpspreadsheet7合并将A到E合并为一个单元格:
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)åºäºphpä¸ä½¿ç¨excelçç®åä»ç»
å¨å·¥ä½ä¸éè¦å¤çå¤è¯è¨çç¿»è¯é®é¢ï¼ç¿»è¯é½æ¯åå¨excelè¡¨æ ¼éé¢ã为äºå¤çæ¹ä¾¿æå°±ä¿çä¸æåè±æ两åãè¿æ ·éè¦å°è¿äºæ°æ®ä»excelä¸ååºæ¥ï¼ç¶ä¹ä¿åå¨excelçæ°ç»ä¸ï¼éè¿ä½¿ç¨å¾ªç¯æ°ç»å°ç¸åºçæ°æ®æ¾å ¥å°æ°æ®åºä¸ã
æ以工ä½ç第ä¸æ¥å°±æ¯è¦å°æ°æ®ä»excelä¸ååºæ¥ãè¿éæ使ç¨å°äºä¸ä¸ªå¼æºphpå¤çexcelç±»ï¼phpexcel.
该项ç®ç详ç»ä¿¡æ¯
/
ã
æç®å使ç¨çæ¯phpexcel1.7.3çæ¬,
解å缩åéé¢æä¸ä¸ªPHPExcelåPHPExcel.phpæ件ã
æ们主è¦ä½¿ç¨é£ä¸ªPHPæ件ãè§ä¸å¾æ件ç®å½ç»æ
è¿ä¸ªçæ¬æ®è¯´æ¯å¯ä»¥æ¯æexcelï¼ä½æ¯æ使ç¨ç¼è¾çxlsxæ¯æ æ³è·å¾è¯¥åºçæ¯æãäºæ¯ä¹æå°±å°å®è½¬å为ãæè§æ¯æå°å¾å¥½ã
ä¸é¢ä»ç»ä¸ä¸å ·ä½ç使ç¨ï¼
å¤å¶ä»£ç
代ç å¦ä¸:
require_once('./phpexcel1.7.3/PHPExcel.php');
$php_excel_obj
=
new
PHPExcel();
$php_reader
=
newPHPExcel_Reader_Excel();
if(!$php_reader->canRead($file_name)){
$php_reader=
new
PHPExcel_Reader_Excel5();
if(!$php_reader->canRead($file_name)){
echo'NO
Excel!';
}
}
$php_excel_obj
=
$php_reader->load($file_name);
$current_sheet
=$php_excel_obj->getSheet(0);
ä¸é¢ç主è¦åè½æ¯åå§åç¸å ³çexcelç±»ï¼å¹¶è£ è½½excel第ä¸ä¸ªsheet
å¤å¶ä»£ç
代ç å¦ä¸:
$all_column
=$current_sheet->getHighestColumn();
$all_row
=$current_sheet->getHighestRow();
以ä¸åå«è·å¾è¯¥è¡¨æ ¼çæ大åå¼(åæ¯è¡¨ç¤ºå¦ï¼âG'),åæ大çè¡æ°ï¼æ°å¼è¡¨ç¤ºï¼
ä¸é¢å°ä½¿ç¨å¾ªç¯æ¥è®²exceléé¢çæ°æ®è¯»å°excelä¸ï¼
å¤å¶ä»£ç
代ç å¦ä¸:
$all_arr
=
array();
$c_arr
=
array();
//åç¬¦å¯¹ç §è¡¨
for($r_i
=
1;
$r_i<=$all_row;
$r_i++){
$c_arr=
array();
for($c_i=
'A';
$c_i<=
'B';
$c_i++){
$adr=
$c_i
.
$r_i;
$value=
$current_sheet->getCell($adr)->getValue();
if($c_i==
'A'
&&
empty($value)
)
break;
if(is_object($value))
$value=
$value->__toString();
$c_arr[$c_i]=
$value;
}
$c_arr&&
$all_arr[]
=
$c_arr;
}
ä¸é¢ç®åå°ä»ç»ä¸ä¸phpexcelçåæä½ï¼è¿ä¸ªæä½ç»å¸¸ç¨äºå°æ°æ®åºä¸çæ°æ®å¯¼å ¥å°excelä¸ï¼ä¾¿äºå±ç¤ºååææ´ç¾è§çææã
å¤å¶ä»£ç
代ç å¦ä¸:
require_once('./phpexcel1.7.3/PHPExcel.php');
$excel_obj
=
new
PHPExcel();
$objWriter
=
newPHPExcel_Writer_Excel5($excel_obj);
$excel_obj->setActiveSheetIndex(0);
$act_sheet_obj=$excel_obj->getActiveSheet();
$act_sheet_obj->setTitle('sheet');
$act_sheet_obj->setCellValue('A1',
'å符串å 容');
$act_sheet_obj->setCellValue('A2',
);
$file_name
=
"output.xls";
$objWriter->save($file_name);
代ç å¾ç®åï¼
é¦å åå§åç¸å ³çexcelåç±»ï¼ç¶ååå ¥æ°æ®ï¼æåä¿å为xlsæ件ã
è¾åºçææè§å¾
php生成excel完整实例代码
下载phpexcel类库 代码如下:
<?php
require_once('PHPExcel.php');
require_once('PHPExcel/IOFactory.php');
$objPHPExcel=new PHPExcel();
$iofactory=new IOFactory();
//获得数据 ---一般是从数据库中获得数据
$data=array(
0=>array('id'=>,'name'=>'张某某','age'=>),
1=>array('id'=>,'name'=>'EVA','age'=>)
);
//设置excel列名
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1','编号');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B1','姓名');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('C1','年龄');
//把数据循环写入excel中
foreach($data as $key => $value){
$key+=2;
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$key,$value['id']);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$key,$value['name']);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$key,$value['age']);
}
//excel保存在根目录下 如要导出文件,以下改为注释代码
$objPHPExcel->getActiveSheet() -> setTitle('SetExcelName');
$objPHPExcel-> setActiveSheetIndex(0);
$objWriter = $iofactory -> createWriter($objPHPExcel, 'Excel');
$objWriter -> save('SetExcelName.xlsx');
//导出代码
// $objPHPExcel->getActiveSheet() -> setTitle('SetExcelName');
// $objPHPExcel-> setActiveSheetIndex(0);
// $objWriter = $iofactory -> createWriter($objPHPExcel, 'Excel');
// $filename = 'SetExcelName.xlsx';
// header('Content-Type: application/vnd.ms-excel');
// header('Content-Type: application/octet-stream');
// header('Content-Disposition: attachment; filename="' . $filename . '"');
// header('Cache-Control: max-age=0');
// $objWriter -> save('php://output');
>2024-12-27 14:04
2024-12-27 13:45
2024-12-27 13:43
2024-12-27 13:11
2024-12-27 12:22
2024-12-27 12:20