Home > php教程 > php手册 > php生成与读取excel文件(.csv)实例

php生成与读取excel文件(.csv)实例

WBOY
Release: 2016-05-25 16:45:00
Original
976 people have browsed it

这里我们是介绍利用php的fgetcsv函数直接来读取.csv文件了,并不是真正的excel文件,如果要读取真正的excel文件我们需要使用插件了,下面我会简单介绍一下.

excel文件(.csv),代码如下:

<?php   
	function getCSVdata($filename)   
	{   
	    $row = 1;//第一行开始   
	    if(($handle = fopen($filename, "r")) !== false)    
	    {   
	        while(($dataSrc = fgetcsv($handle)) !== false)    
	        {   
	            $num = count($dataSrc);   
	            for ($c=0; $c < $num; $c++)//列 column    
	            {   
	                if($row === 1)//第一行作为字段    
	                {   
	                    $dataName[] = $dataSrc[$c];//字段名称   
	                }   
	                else   
	                {   
	                    foreach ($dataName as $k=>$v)   
	                    {   
	                        if($k == $c)//对应的字段   
	                        {   
	                            $data[$v] = $dataSrc[$c];   
	                        }   
	                    }   
	                }   
	            }   
	            if(!emptyempty($data))   
	            {   
	                 $dataRtn[] = $data;   
	                 unset($data);   
	            }   
	            $row++;   
	        }   
	        fclose($handle);   
	        return $dataRtn;   
	    }   
	}   
	   
	$aData = getCSVdata(&#39;all_.csv&#39;);   
	 
	foreach ($aData as $k=>$v ){ 
	echo "http://".$v[&#39;a&#39;]."<br>"; 
	} 
	   
Copy after login

生成excel文件(csv),代码如下:

<?php 
	header("Content-type:application/vnd.ms-excel"); 
	header("Content-Disposition:attachment;filename=test_data.xls"); 
	//输出内容如下:  
	echo   "姓名"."t";  
	echo   "年龄"."t";  
	echo   "学历"."t";  
	echo   "n";  
	echo   "张三"."t";  
	echo   "25"."t";  
	echo   "本科"."t";  
	 
Copy after login

上面只是简单的一些excel文件操作,如果说进行如编辑,修改,删除行表格操作我们可使用phpexcel插件来操作excel文件了.

教程地址:

欢迎转载!但请带上文章地址^^

Related labels:
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template