php 从phpExcel中的Db获取数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 从phpExcel中的Db获取数据相关的知识,希望对你有一定的参考价值。

<?php

/* Col Name*/
function createColumnsArray($end_column, $first_letters = '')
{
  $columns = array();
  $length = strlen($end_column);
  $letters = range('A', 'Z');
  

  // Iterate over 26 letters.
  foreach ($letters as $letter) {
	  
	
	  
      // Paste the $first_letters before the next.
      $column = $first_letters . $letter;

      // Add the column to the final array.
      $columns[] = $column;

      // If it was the end column that was added, return the columns.
      if ($column == $end_column)
          return $columns;
  }

  // Add the column children.
  foreach ($columns as $column) {
      // Don't itterate if the $end_column was already set in a previous itteration.
      // Stop iterating if you've reached the maximum character length.
      if (!in_array($end_column, $columns) && strlen($column) < $length) {
          $new_columns = createColumnsArray($end_column, $column);
          // Merge the new columns which were created with the final columns array.
          $columns = array_merge($columns, $new_columns);
      }
  }


	//start with ket=>1 in php
	$export_array = $columns;
	$export_array = array_filter(array_merge(array(0), $export_array));
	
  
  return $export_array;
}

/* PHPExcel export */
function phpexcel($sheetname,$field,$data,$file_pishvand = false,$auto_row = false) {

    /*Example
    $f = array(
        array("name" => "esm", "size" => "", "link" => "yes"),
        array("name" => "email", "size" => "auto", "link" => "no"),
        array("name" => "سال", "size" => "auto", "link" => "no"),
    );
    $data = array(
    array("View profile|||http://www.irwebdesign.ir","mehrshadhjg198@gmail.com","28"),
    array("View profile|||http://www.mehdi.net","mehrshad198@gmail.com","45"),
    );

    echo phpexcel("me",$f,$data);
    */
    /** Include PHPExcel */
    require_once (trailingslashit(ABSPATH).'wp-content/plugins/wp-maskan/phpexcel/PHPExcel.php');

// Create new PHPExcel object
    $objPHPExcel = new PHPExcel();

// Set document properties
    $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
        ->setLastModifiedBy("Maarten Balliauw")
        ->setTitle("Office 2007 XLSX Test Document")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory("Test result file");

// Rename worksheet
    $objPHPExcel->getActiveSheet()->setTitle($sheetname);
    $objPHPExcel->getActiveSheet()->setRightToLeft(true);
    $objPHPExcel->getDefaultStyle()->getFont()->setName('tahoma')->setSize(11);

    $objPHPExcel->getActiveSheet()
        ->getStyle('A1:Z1')
        ->applyFromArray(
            array(
                'fill' => array(
                    'type' => PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => '18A689')
                ),
            )
        );
    $objPHPExcel->getActiveSheet()->getStyle('A1:Z1')->applyFromArray(array('font' => array('color' => array('rgb' => 'ffffff'))));
    $objPHPExcel->setActiveSheetIndex(0);

//Array
    $arr= createColumnsArray('CC');
    $link = array();
    $head = array();

    if($auto_row) { $head[] = $auto_row;  $x=1; } else { $x = 0;}

    foreach($field as $header) {
        $head[] = $header['name'];
        if($header['link'] =="yes") {
            $link[] = $x;
        }
        $x++;
    }
    $objPHPExcel->getActiveSheet()->fromArray($head, null, 'A1');

//add auto number in data
    if($auto_row) {
        for($m=0; $m<count($data); $m++) {
            array_unshift($data[$m],($m + 1));
        }
    }

//replace link data
    if(count($link >0)) {
        $list_link = array();
        for($z=0; $z<count($data); $z++) {
            foreach($link as $p) {
                $new_array=explode("|||",$data[$z][$p]); //[0] view [1] link
                $list_link[$z] = $new_array[1];
                $data[$z][$p] = $new_array[0];
            }
        }
    }

    $objPHPExcel->getActiveSheet()->fromArray($data, null, 'A2');

//set link for data
    if(count($link >0)) {
        for($q=1; $q<=count($data); $q++) {
            foreach($link as $p) {

                //if auto number
                $objPHPExcel->getActiveSheet()->getCell($arr[$p + 1].($q + 1))->getHyperlink()->setUrl($list_link[$q - 1]);
                $objPHPExcel->getActiveSheet()->getStyle($arr[$p + 1].($q + 1))->applyFromArray(array('font' => array('color' => array('rgb' => '0000ff'))));

            }
        }
    }

//setu auto size
    if($auto_row) { $objPHPExcel->getActiveSheet()->getColumnDimension($arr[1])->setAutoSize(true); $t = 2; } else { $t = 1; }
    foreach($field as $header) {
        if($header['size'] =="auto") {
            $objPHPExcel->getActiveSheet()->getColumnDimension($arr[$t])->setAutoSize(true);
        }
        $t++;
    }
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

    //save file
    $upload_dir = wp_upload_dir(); // Grab uploads folder array
    $dir = trailingslashit( $upload_dir['basedir'] ) . 'excel/'; // Set storage directory path
	
	//Remove All file From this directory
	foreach(glob($dir.'*.*') as $v){
		@unlink($v);
	}
	
    if($file_pishvand) {
        $pish = $file_pishvand;
    } else {
        $pish = "CMS-Excel";
    }
    $file_name = $pish."-".date('Y-m-d-His').".xls";

    $objWriter->save($dir.$file_name);
    return home_url().'/wp-content/uploads/excel/'.$file_name;
    wp_die();
}
<?php

   //load phpexcel
        require_once ('phpexcel.php');

        $list_field = array(
            array("name" => "تاریخ ثبت نام", "size" => "auto", "link" => "no"),
            array("name" => "آی پی کاربر", "size" => "auto", "link" => "no"),
            array("name" => "کد رهگیری", "size" => "auto", "link" => "no"),
        );

        $list_col_table = array();

        $Query = $wpdb->get_results("SELECT * FROM `".TABLE_AR_HELP."` ORDER BY id ASC LIMIT 3,4", ARRAY_A);
        foreach ( $Query as $row ) {
            for ($i=$row['from'];$i<=$row['to'];$i++) {
                $list_col_table[] = wp_get_col_name($i-1);
                $col_comment = wp_get_col_comment($i-1);
                $list_field[]= array("name" => $col_comment, "size" => "auto", "link" => "no");
            } //End for
        }

        //remove last item
        //array_pop($list_field);
        //array_pop($list_col_table);
	    $list_field[]= array("name" => "لینک آخرین خبر", "size" => "auto", "link" => "no");
	    $list_field[]= array("name" => "تعداد اعضای گروه/کانال", "size" => "auto", "link" => "no");


        //data for  excel
        $data = array();

        if($_GET['excel_id'] =="ALL") {
            $sql = "SELECT * FROM ra_list";
        } else {
            $sql = "SELECT * FROM ra_list where cid={$_GET['excel_id']}";
        }
        $query = $wpdb->get_results($sql, ARRAY_A);

        foreach ( $query as $row ) {

            $field = array(
                parsidate('l j F Y ساعت H:i',$row['data-reg'],$lang='per'),
                $row['ip'],
                $row['code-rahgiry']
            );

            foreach($list_col_table as $item) {
                if($item =="cid") {

                	if($row['type'] =="منزل") {
		                $field[] = "-";
	                } else {
		                $field[] = get_cid_name( $row[$item] );
	                }

                } else {
                    if(trim($row[$item]) =="") {
                        $field[] = "-";
                    } else {
                        $field[] = $row[$item];
                    }
                }
            }
	        $field[] = $row['example_link'];
	        $field[] = $row['user_soroush'];
            $data[] = $field;
        }

//        echo "<pre>";
//        print_r($data);
//        exit;



        //export Excel
        $link = phpexcel('لیست گزارش',$list_field,$data,$file_pishvand = 'shabab',"ردیف");
        echo '
			<div id="alert-id">
			<div class="well text-right rtl"><a style="text-decoration:none;" href="'.$link.'"><span class="dashicons dashicons-admin-links"></span> دریافت فایل گزارش با فرمت اکسل</a></div>
			</div>';

以上是关于php 从phpExcel中的Db获取数据的主要内容,如果未能解决你的问题,请参考以下文章

php 图表的操作

从 db 获取数据并通过 PHP 中的 Mailchimp 发送邮件

php excel文件导出之phpExcel扩展库

php获取excel文件数据

PHPExcel将Excel数据导入数据库

从db获取数据并通过PHP中的Mailchimp发送邮件