PHP 读写Excel 和 CSV 文件

来源:互联网 发布:淘宝网妈妈秋装 编辑:程序博客网 时间:2024/06/01 07:20
    本文使用的PHP 读写Excel 和 CSV 文件的使用的开源的PHPExcel 框架,该框架功能很全。 可以读写xls,xlsx,csv ,ods,html ,甚至是pdf 。功能很强大,源代码见
https://github.com/PHPOffice/PHPExcel
文档也很详细:
https://github.com/PHPOffice/PHPExcel/blob/1.8/Documentation/PHPExcel%20developer%20documentation.doc

本文的功能主要是通过PHPExcel 完成,读取Excel 中指定的行和列,写入到CSV 文件中的行和列。目的就是格式话Excel 文件的数据的输出。
代码也比较简单直接上代码:
<?phprequire_once dirname(__FILE__) . '/Classes/PHPExcel/IOFactory.php';//input output and template file name$inputFile = "test.xlsx";$templateFile = "templet.csv";$outputFile = "templet_out.csv";//deal with php argumentsfor($i = 1;$i< $argc;$i++) {    switch($argv[$i]) {        case "-i": $inputfile = $argv[$i+1];break;        case "-o": $outputfile = $argv[$i+1];break;        default:break;    }}echo "\$inputfile = $inputFile , \$outputfile = $outputFile \n";//load input excel file.$objPHPExcel = PHPExcel_IOFactory::load($inputFile);//load csv file as excel object$objReader = PHPExcel_IOFactory::createReader('CSV')->setDelimiter(',')                                                    ->setEnclosure('"')                                                    ->setSheetIndex(0);$objPHPExcelFromCSV = $objReader->load($templateFile);//read the excel and write csv file.$index = 2;while(1) {    $id = $objPHPExcel->getActiveSheet()->getCell('A'.$index)->getValue();    $des = $objPHPExcel->getActiveSheet()->getCell('C'.$index)->getValue();    if($id != "") {        $objPHPExcelFromCSV->getActiveSheet()->getCell('B'.$index)->setValue($id);        $objPHPExcelFromCSV->getActiveSheet()->getCell('C'.$index)->setValue($des);        $objPHPExcelFromCSV->getActiveSheet()->getCell('A'.$index)->setValue("/Test(#7)");        $objPHPExcelFromCSV->getActiveSheet()->getCell('F'.$index)->setValue("功能测试");        echo $id."\n";    } else {        break;    }    $index++;}echo "convert success count = ".($index-2)."\n";//save output file .$objWriterCSV = PHPExcel_IOFactory::createWriter($objPHPExcelFromCSV, 'CSV');$objWriterCSV->setUseBOM(true);$objWriterCSV->save($outputFile);

    本文的php 文件是在linux 下面使用脚本php xxx.php 来执行的,也可以使用http 来解析。 执行php 文件之前需要靠本PHPExcel 目录下的Classes 到和php 同目录下。

    更多的使用和方法,我推荐看PHPExcel 提供的英文文档,如果对自己英文没有信心可以看一下:

   http://blog.csdn.net/beyond__devil/article/details/53457849

里面讲解了官方文档中的几个例子,可以看一下。

原创粉丝点击