Chinaunix首页 | 论坛 | 博客
  • 博客访问: 273320
  • 博文数量: 59
  • 博客积分: 1368
  • 博客等级: 中尉
  • 技术积分: 1071
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-02 06:06
文章分类

全部博文(59)

文章存档

2012年(59)

我的朋友

分类: 系统运维

2012-02-16 14:55:41

1 使用fgetcsv函数
array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = ',' [, string $enclosure = '"' [, string $escape = '\\' ]]]] )
  1. <?php
  2. $row = 1;
  3. if (($handle = fopen("test.csv", "r")) !== FALSE) {
  4.     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
  5.         $num = count($data);
  6.         echo "

    $num fields in line $row:

    \n"
    ;
  7.         $row++;
  8.         for ($c=0; $c < $num; $c++) {
  9.             echo $data[$c] . "
    \n"
    ;
  10.         }
  11.     }
  12.     fclose($handle);
  13. }
  14. ?>
2 phpExcelReader

3 PHPExcel

3.1 使用PHPExcel_IOFactory读取
  1. <?php
  2. require_once 'PHPExcel/IOFactory.php';
  3. $objPHPExcel = PHPExcel_IOFactory::load("test.xlsx");
  4. //$sheet = $objPHPExcel->getSheet(0);

  5. foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
  6.     $worksheetTitle = $worksheet->getTitle();
  7.     $highestRow = $worksheet->getHighestRow(); // e.g. 10
  8.     $highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
  9.     $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
  10.     $nrColumns = ord($highestColumn) - 64;
  11.     echo "
    The worksheet "
    .$worksheetTitle." has ";
  12.     echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
  13.     echo ' and ' . $highestRow . ' row.';
  14.     echo '
    Data: ';
  15.     for ($row = 1; $row <= $highestRow; ++ $row) {
  16.         echo '
  17. ';
  18.         for ($col = 0; $col < $highestColumnIndex; ++ $col) {
  19.             $cell = $worksheet->getCellByColumnAndRow($col, $row);
  20.             $val = $cell->getValue();
  21.             $dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
  22.             echo '
  23. ';
  24.         }
  25.         echo '
  26. ';
  27.     }
  28.     echo '
  29. ' . $val . '
    (Typ '
    . $dataType . ')
    '
    ;
  30. }
3.2使用PHPExcel_Reader_Excel2007读取
  1. <?php
  2. include 'PHPExcel.php';
  3. include 'PHPExcel/Reader/Excel2007.php';
  4. include 'PHPExcel/Reader/Excel5.php';
  5. $fileName = 'test.xlsx';

  6. $PHPExcel = new PHPExcel();

  7. $PHPReader = new PHPExcel_Reader_Excel2007();
  8. if (!$PHPReader->canRead($fileName))
  9. {
  10.     $PHPReader = new PHPExcel_Reader_Excel5();
  11.     if (!$PHPReader->canRead($fileName))
  12.     {
  13.         echo 'no Excel';
  14.         exit;
  15.     }
  16. }

  17. $PHPExcel = $PHPReader->load($fileName);
  18. $currentSheet = $PHPExcel->getSheet(0);
  19. $allColumn = $currentSheet->getHighestColumn();
  20. $allRow = $currentSheet->getHighestRow();

  21. for($currentRow = 2; $currentRow<=$allRow; $currentRow++)
  22. {
  23.     for($currentColumn='A'; $currentColumn<=$allColumn; $currentColumn++)
  24.     {
  25.         $address = $currentColumn.$currentRow;
  26.         echo $currentSheet->getCell($address)->getValue()."\t";
  27.     }
  28.     echo "
    "
    ;
  29. }
3.3 使用RowIterator和CellIterator迭代读取
  1. <?php

  2. error_reporting(E_ALL);
  3. ini_set('include_path', ini_get('include_path').';./Classes/');

  4. include 'PHPExcel.php';
  5. include 'PHPExcel/Reader/Excel2007.php';

  6. $objReader = new PHPExcel_Reader_Excel2007();
  7. $objReader->setReadDataOnly(true);
  8. $objPHPExcel = $objReader->load('test.xlsx');
  9. $rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
  10. $sheet = $objPHPExcel->getActiveSheet();
  11. $array_data = array();

  12. foreach($rowIterator as $row){
  13.     $cellIterator = $row->getCellIterator();
  14.     $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
  15.     if(1 == $row->getRowIndex ()) continue;//skip first row
  16.     $rowIndex = $row->getRowIndex ();
  17.     $array_data[$rowIndex] = array('A'=>'', 'B'=>'','C'=>'','D'=>'');
  18.  
  19.     foreach ($cellIterator as $cell) {
  20.         if('A' == $cell->getColumn()){
  21.             $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
  22.         } else if('B' == $cell->getColumn()){
  23.             $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
  24.         } else if('C' == $cell->getColumn()){
  25.             $array_data[$rowIndex][$cell->getColumn()] = PHPExcel_Style_NumberFormat::toFormattedString($cell->getCalculatedValue(), 'YYYY-MM-DD');
  26.         } else if('D' == $cell->getColumn()){
  27.             $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
  28.         }
  29.     }
  30.     /*
  31.     $rowIndex = $row->getRowIndex ();
  32.     $array_data[$rowIndex] = array('A'=>'', 'B'=>'','C'=>'','D'=>'');
  33.  
  34.     $cell = $sheet->getCell('A' . $rowIndex);
  35.     $array_data[$rowIndex]['A'] = $cell->getCalculatedValue();
  36.     $cell = $sheet->getCell('B' . $rowIndex);
  37.     $array_data[$rowIndex]['B'] = $cell->getCalculatedValue();
  38.     $cell = $sheet->getCell('C' . $rowIndex);
  39.     $array_data[$rowIndex]['C'] = PHPExcel_Style_NumberFormat::toFormattedString($cell->getCalculatedValue(), 'YYYY-MM-DD');
  40.     $cell = $sheet->getCell('D' . $rowIndex);
  41.     $array_data[$rowIndex]['D'] = $cell->getCalculatedValue();*/
  42. }
  43. var_dump($array_data);
3.4 使用PHPExcel_Writer_Excel2007写入
  1. <?php

  2. error_reporting(E_ALL);
  3. ini_set('include_path', ini_get('include_path').';./Classes/');

  4. include 'PHPExcel.php';
  5. include 'PHPExcel/Writer/Excel2007.php';
  6. //include 'PHPExcel/Writer/Excel5.php';

  7. $objPHPExcel = new PHPExcel();
  8. /* set properties */
  9. //$objPHPExcel->getProperties()->setCreator("Maarten Balliauw"); // 作者
  10. //$objPHPExcel->getProperties()->setLastModifiedBy("Jone Smith");
  11. //$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document"); //标题
  12. //$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document"); //主题
  13. //$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes."); //备注
  14. //$objPHPExcel->getProperties()->setKeywords("office 2007 openxml php"); //关键字
  15. //$objPHPExcel->getProperties()->setCategory("Test result file"); //类别

  16. /* set content */
  17. //$objPHPExcel->setActiveSheetIndex(0);
  18. //$objPHPExcel->getActiveSheet()->setTitle('Simple');
  19. //$objPHPExcel->getActiveSheet()->setCellValue('A1', 'String');
  20. //$objPHPExcel->getActiveSheet()->setCellValue('A2', 12);
  21. //$objPHPExcel->getActiveSheet()->setCellValue('A3', true);
  22. //$objPHPExcel->getActiveSheet()->setCellValue('C5', '=SUM(C2:C4)');
  23. //$objPHPExcel->getActiveSheet()->setCellValue('B8', '=MIN(B2:C5)');
  24. //$objPHPExcel->getActiveSheet()->mergeCells('A18:E22'); //合并单元格
  25. //$objPHPExcel->getActiveSheet()->unmergeCells('A28:B28'); //分离单元格
  26. //$objPHPExcel->getActiveSheet()->setCellValueExplicit('A5', '847475847857487584', PHPExcel_Cell_DataType::TYPE_STRING);

  27. /* 保护cell */
  28. //$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
  29. //$objPHPExcel->getActiveSheet()->protectCells('A3:E13', 'PHPExcel');

  30. /* cell 数字格式 */
  31. //$objPHPExcel->getActiveSheet()->getStyle('E4')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);
  32. //$objPHPExcel->getActiveSheet()->getStyle('E4')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
  33. //$objPHPExcel->getActiveSheet()->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle('E4'), 'E5:E13' );

  34. /* column width */
  35. //$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
  36. //$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
  37. //$ojStyleA5 = $objPHPExcel->getActiveSheet()->getStyle('A5');

  38. /* set font */
  39. //$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setName('Candara');
  40. //$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setSize(20);
  41. //$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
  42. //$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
  43. //$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
  44. //$objPHPExcel->getActiveSheet()->getStyle('E1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
  45. //$objPHPExcel->getActiveSheet()->getStyle('D13')->getFont()->setBold(true);
  46. //$objPHPExcel->getActiveSheet()->getStyle('E13')->getFont()->setBold(true);

  47. /* set align */
  48. //$objPHPExcel->getActiveSheet()->getStyle('D11')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
  49. //$objPHPExcel->getActiveSheet()->getStyle('D12')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
  50. //$objPHPExcel->getActiveSheet()->getStyle('D13')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
  51. //$objPHPExcel->getActiveSheet()->getStyle('A18')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);
  52. //$objPHPExcel->getActiveSheet()->getStyle('A18')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

  53. /* set column border */
  54. //$objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getLeft()->getColor()->setARGB(’FF993300′);
  55. //$objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getTop()->getColor()->setARGB(’FF993300′);
  56. //$objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getBottom()->getColor()->setARGB(’FF993300′);
  57. //$objPHPExcel->getActiveSheet()->getStyle('E13')->getBorders()->getTop()->getColor()->setARGB(’FF993300′);
  58. //$objPHPExcel->getActiveSheet()->getStyle('E13')->getBorders()->getBottom()->getColor()->setARGB(’FF993300′);
  59. //$objPHPExcel->getActiveSheet()->getStyle('E13')->getBorders()->getRight()->getColor()->setARGB(’FF993300′);
  60. //$objPHPExcel->getActiveSheet()->getStyle('E13')->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
  61. /*
  62. $default_border = array(
  63. 'style' => PHPExcel_Style_Border::BORDER_THIN,
  64. 'color' => array('rgb'=>'1006A3')
  65. );
  66. $style_header = array(
  67. 'borders' => array(
  68. 'bottom' => $default_border,
  69. 'left' => $default_border,
  70. 'top' => $default_border,
  71. 'right' => $default_border,
  72. ),
  73. 'fill' => array(
  74. 'type' => PHPExcel_Style_Fill::FILL_SOLID,
  75. 'color' => array('rgb'=>'E1E0F7'),
  76. ),
  77. 'font' => array(
  78. 'bold' => true,
  79. )
  80. );

  81. $sheet->getStyle('A1:A2')->applyFromArray( $style_header );
  82. $sheet->getStyle('B1:B2')->applyFromArray( $style_header );
  83. */

  84. /* fill color */
  85. //$objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
  86. //$objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setARGB(’FF808080′);
  87. //$objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
  88. //$objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->getStartColor()->setARGB(’FF808080′);

  89. /* copy style */
  90. //$objPHPExcel->getActiveSheet()->duplicateStyle($objStyleA5, 'B1:C22');

  91. /* add image */
  92. /*
  93. $objDrawing = new PHPExcel_Worksheet_Drawing();
  94. $objDrawing->setName(’Logo’);
  95. $objDrawing->setDescription(’Logo’);
  96. $objDrawing->setPath(’./images/officelogo.jpg’);
  97. $objDrawing->setHeight(36);
  98. $objDrawing->setCoordinates('B15');
  99. $objDrawing->setOffsetX(110);
  100. $objDrawing->setRotation(25);
  101. $objDrawing->getShadow()->setVisible(true);
  102. $objDrawing->getShadow()->setDirection(45);
  103. $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
  104. */

  105. /* add a new worksheet */
  106. //$objPHPExcel->createSheet();
  107. //$objPHPExcel->getSheet(1)->setTitile('sheet2');
  108. //$objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
  109. //$objWriter->save('php://output');

  110. /* add summary/total row *//
  111. /*
  112. //Adding total column
  113. $ranged_total_coordinate = chr($starting_pos+$index_pos) . '1:' . chr($starting_pos+$index_pos) . '2';
  114. $sheet->setCellValue(chr($starting_pos+$index_pos) . '1', 'Total');
  115. $sheet->mergeCells($ranged_total_coordinate);
  116. $sheet->getStyle(chr($starting_pos+$index_pos) . '1')->getAlignment()
  117. ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
  118. ->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP);
  119. $sheet->getStyle($ranged_total_coordinate)->applyFromArray( $style_header );
  120. $rowcounter = 2;
  121. foreach($array_data_user as $k1=>$v1){
  122. $rowcounter++;
  123. $sheet->setCellValue(chr($starting_pos+$index_pos) . $rowcounter, "=SUM(C{$rowcounter}:".chr(($starting_pos+($index_pos-1)))."{$rowcounter})");
  124. $sheet->getStyle(chr($starting_pos+$index_pos) . $rowcounter)->applyFromArray( $style_body_content );
  125. }
  126. */

  127. /* parsing formula */
  128. //$sheet->getCell('K3')->getValue() . " -> " . $sheet->getCell('K3')->getCalculatedValue();

  129. $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
  130. //$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);

  131. /* create empty Excel */
  132. $objWriter->save('xxx.xlsx');

  133. /* force download */
  134. /*
  135. header('Pragma: public');
  136. header('Expires: 0');
  137. header('Cache-Control:must-revalidate, post-check=0, pre-check=0');
  138. header('Content-Type:application/force-download');
  139. header('Content-Type:application/vnd.ms-execl');
  140. header('Content-Type:application/octet-stream');
  141. header('Content-Type:application/download');;
  142. header('Content-Disposition:attachment;filename="resume.xlsx"');
  143. header('Content-Transfer-Encoding:binary');
  144. $objWriter->save('php://output');*/


3.5 合并多个excel文件至一个
  1. <?php

  2. include 'PHPExcel/IOFactory.php';

  3. $inputFileType = 'CSV';
  4. $inputFileNames = array('./example1.csv','./example2.csv','./example3.csv','./example4.csv');

  5. $objReader = PHPExcel_IOFactory::createReader($inputFileType);
  6. $inputFileName = array_shift($inputFileNames);
  7. $objPHPExcel = $objReader->load($inputFileName);
  8. $objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
  9. foreach($inputFileNames as $sheet => $inputFileName) {
  10.     $objReader->setSheetIndex($sheet+1);
  11.     $objReader->loadIntoExisting($inputFileName,$objPHPExcel);
  12.     $objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
  13. }


  14. $loadedSheetNames = $objPHPExcel->getSheetNames();
  15. foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
  16.     $objPHPExcel->setActiveSheetIndexByName($loadedSheetName);
  17.     echo $loadedSheetName,PHP_EOL;
  18.     $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
  19.     var_dump($sheetData);
  20.     echo PHP_EOL;
  21. }
3.6 格式转换
  1. <?php

  2. $cell = $objWorksheet->getCellByColumnAndRow(3, 5);
  3. $cell_value = PHPExcel_Style_NumberFormat::toFormattedString($cell->getCalculatedValue(), 'hh:mm:ss');
  4. echo $cell_value;
3.5 格式转换
  1. <?php

  2. $objPHPExcel = PHPExcel_IOFactory::load("XMLTest.xml");
  3. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  4. $objWriter->save('covertedXml2Xlsx.xlsx');
阅读(1155) | 评论(0) | 转发(0) |
0

上一篇:SQLite 笔记

下一篇:php - 时间函数应用

给主人留下些什么吧!~~