簡體   English   中英

如何使用PHPExcel將數據導出到excel文件

[英]How to export data to an excel file using PHPExcel

我已從limesurvey 獲取源代碼,並將PHPExcel 庫添加到我的limesurvey 代碼中,以便在您單擊鏈接后將數據導出到excel 文件中。 目前,excel 文件打開時有一些虛擬數據,沒有任何問題。 在用戶輸入調查信息后,我需要能夠從 Web 服務器動態添加數據。 我查看了我發現的一些網站,但我沒有太多運氣。 誰能幫我嗎?

編輯

<?php 
$dbhost= "mysql"; //your MySQL Server 
$dbuser = "survey"; //your MySQL User Name 
$dbpass = "password"; //your MySQL Password 
$dbname = "database"; 
//your MySQL Database Name of which database to use this 
$tablename = "questions"; //your MySQL Table Name which one you have to create excel file 
// your mysql query here , we can edit this for your requirement 
$sql = "Select * from $table "; 
//create  code for connecting to mysql 
$Connect = @mysql_connect($dbhost, $dbuser, $dbpass) 
or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno()); 
//select database 
$Db = @mysql_select_db($dbname, $Connect) 
or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno()); 
//execute query 
$result = @mysql_query($sql,$Connect) 
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno()); 

error_reporting(E_ALL);

 require_once '../Classes/PHPExcel.php';
 $objPHPExcel = new PHPExcel();

 // Set the active Excel worksheet to sheet 0 

$objPHPExcel->setActiveSheetIndex(0);  

// Initialise the Excel row number 

$rowCount = 1;  


//start of printing column names as names of MySQL fields  

 $column = 'A';

for ($i = 1; $i < mysql_num_fields($result); $i++)  

{
    $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
    $column++;
}

//end of adding column names  
//start while loop to get data  

$rowCount = 2;  

while($row = mysql_fetch_row($result))  

{  
    $column = 'A';

   for($j=1; $j<mysql_num_fields($result);$j++)  
    {  
        if(!isset($row[$j]))  

            $value = NULL;  

        elseif ($row[$j] != "")  

            $value = strip_tags($row[$j]);  

        else  

            $value = "";  


        $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
        $column++;
    }  

    $rowCount++;
} 

// Redirect output to a client’s web browser (Excel5) 
header('Content-Type: application/vnd.ms-excel'); 
header('Content-Disposition: attachment;filename="results.xls"'); 
header('Cache-Control: max-age=0'); 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
$objWriter->save('php://output');

如果你直接復制了這個,那么:

->setCellValue('B2', Ackermann') 

應該

->setCellValue('B2', 'Ackermann') 

回答你的問題:

從limesurvey 獲取您想要的數據,並使用setCellValue() 將這些數據值存儲在您想要存儲它的單元格中。

/Tests 中的 Quadratic.php 示例文件可能有助於作為起點:它從輸入表單中獲取數據並將其設置為 Excel 工作簿中的單元格。

編輯

一個極其簡單的例子:

// Create your database query
$query = "SELECT * FROM myDataTable";  

// Execute the database query
$result = mysql_query($query) or die(mysql_error());

// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel(); 
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0); 
// Initialise the Excel row number
$rowCount = 1; 
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while($row = mysql_fetch_array($result)){ 
    // Set cell An to the "name" column from the database (assuming you have a column called name)
    //    where n is the Excel row number (ie cell A1 in the first row)
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['name']); 
    // Set cell Bn to the "age" column from the database (assuming you have a column called age)
    //    where n is the Excel row number (ie cell A1 in the first row)
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['age']); 
    // Increment the Excel row counter
    $rowCount++; 
} 

// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('some_excel_file.xlsx'); 

編輯#2

使用您現有的代碼作為基礎

// Instantiate a new PHPExcel object 
$objPHPExcel = new PHPExcel();  
// Set the active Excel worksheet to sheet 0 
$objPHPExcel->setActiveSheetIndex(0);  
// Initialise the Excel row number 
$rowCount = 1;  

//start of printing column names as names of MySQL fields  
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)  
{
    $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
    $column++;
}
//end of adding column names  

//start while loop to get data  
$rowCount = 2;  
while($row = mysql_fetch_row($result))  
{  
    $column = 'A';
    for($j=1; $j<mysql_num_fields($result);$j++)  
    {  
        if(!isset($row[$j]))  
            $value = NULL;  
        elseif ($row[$j] != "")  
            $value = strip_tags($row[$j]);  
        else  
            $value = "";  

        $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
        $column++;
    }  
    $rowCount++;
} 


// Redirect output to a client’s web browser (Excel5) 
header('Content-Type: application/vnd.ms-excel'); 
header('Content-Disposition: attachment;filename="Limesurvey_Results.xls"'); 
header('Cache-Control: max-age=0'); 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
$objWriter->save('php://output');

嘗試以下完整示例

<?php
  $objPHPExcel = new PHPExcel();
  $query1 = "SELECT * FROM employee";
  $exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
  $serialnumber=0;
  //Set header with temp array
  $tmparray =array("Sr.Number","Employee Login","Employee Name");
  //take new main array and set header array in it.
  $sheet =array($tmparray);

  while ($res1 = mysql_fetch_array($exec1))
  {
    $tmparray =array();
    $serialnumber = $serialnumber + 1;
    array_push($tmparray,$serialnumber);
    $employeelogin = $res1['employeelogin'];
    array_push($tmparray,$employeelogin);
    $employeename = $res1['employeename'];
    array_push($tmparray,$employeename);   
    array_push($sheet,$tmparray);
  }
   header('Content-type: application/vnd.ms-excel');
   header('Content-Disposition: attachment; filename="name.xlsx"');
  $worksheet = $objPHPExcel->getActiveSheet();
  foreach($sheet as $row => $columns) {
    foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
    }
  }

  //make first row bold
  $objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
  $objPHPExcel->setActiveSheetIndex(0);
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>
$this->load->library('excel');
$file_name = 'Demo';
$arrHeader = array('Name', 'Mobile');
$arrRows = array(0=>array('Name'=>'Jayant','Mobile'=>54545), 1=>array('Name'=>'Jayant1', 'Mobile'=>44454), 2=>array('Name'=>'Jayant2','Mobile'=>111222), 3=>array('Name'=>'Jayant3', 'Mobile'=>99999));
$this->excel->getActiveSheet()->fromArray($arrHeader,'','A1');
$this->excel->getActiveSheet()->fromArray($arrRows);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$file_name.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');  
$objWriter->save('php://output');

工作 100%。 可能與創建者答案無關,但我與用戶分享它,因為用戶在使用 phpexcel 將 mysql 查詢導出到 excel 時遇到問題。 祝你好運。

require('../phpexcel/PHPExcel.php');

require('../phpexcel/PHPExcel/Writer/Excel5.php');

$filename = 'userReport'; //your file name

    $objPHPExcel = new PHPExcel();
    /*********************Add column headings START**********************/
    $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', 'username')
                ->setCellValue('B1', 'city_name');

    /*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
  $user_name = $value['username'];
  $c_code = $value['city_name'];
  $num_row++;
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$num_row, $user_name )
                ->setCellValue('B'.$num_row, $c_code );
}

    /*********************Autoresize column width depending upon contents START**********************/
    foreach(range('A','B') as $columnID) {
        $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
    }
    $objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);



//Make heading font bold

        /*********************Add color to heading START**********************/
        $objPHPExcel->getActiveSheet()
                    ->getStyle('A1:B1')
                    ->getFill()
                    ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
                    ->getStartColor()
                    ->setARGB('99ff99');

        $objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;Filename=$filename.xls");
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

經過一系列谷歌搜索從sql語句下載excel文件后,我目前在我的項目中使用此功能

    // $sql = sql query e.g "select * from mytablename"
    // $filename = name of the file to download 
        function queryToExcel($sql, $fileName = 'name.xlsx') {
                // initialise excel column name
                // currently limited to queries with less than 27 columns
        $columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
                // Execute the database query
                $result =  mysql_query($sql) or die(mysql_error());

                // Instantiate a new PHPExcel object
                $objPHPExcel = new PHPExcel();
                // Set the active Excel worksheet to sheet 0
                $objPHPExcel->setActiveSheetIndex(0);
                // Initialise the Excel row number
                $rowCount = 1;
    // fetch result set column information
                $finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter                
$columnlenght = 0;
                foreach ($finfo as $val) {
// set column header values                   
  $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
                }
// make the column headers bold
                $objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);

                $rowCount++;
                // Iterate through each result from the SQL query in turn
                // We fetch each database result row into $row in turn

                while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
                    for ($i = 0; $i < $columnLenght; $i++) {
                        $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
                    }
                    $rowCount++;
                }
// set header information to force download
                header('Content-type: application/vnd.ms-excel');
                header('Content-Disposition: attachment; filename="' . $fileName . '"');
                // Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file        
                // Write the Excel file to filename some_excel_file.xlsx in the current directory                
                $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
                // Write the Excel file to filename some_excel_file.xlsx in the current directory
                $objWriter->save('php://output');
            }
// gl and gl2 excel file Export Program
public function glExcelFileExport()
{
    $from_date1 = $this->input->post('from_date1');
    $to_date1 = $this->input->post('to_date1');
    $account_number = $this->input->post('account_number');
    $glnames = $this->input->post('glnames');

    $sql = "SELECT * FROM ut_sbi_reco_rungl WHERE value_date between '".$from_date1."' AND '".$to_date1."' ";
    $result = $this->db->query($sql)->result_array();

    if(count($result)>0)
    {
        require FCPATH . 'vendor/autoload.php';

        $object = new PHPExcel();

        $prestasi = $object->setActiveSheetIndex(0); 

        //manage row hight

        $object->getActiveSheet()->getRowDimension(1)->setRowHeight(25);


        // Excel Heading Description
        if($glnames == 'gl1') {

        //style alignment

        $styleArray = array(

            'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,

                'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,

            ),

        );

        $object->getActiveSheet()->getStyle('A1:U1')->getFont()->setBold(true);

        $object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray);

        //border

        $styleArray1 = array(

            'borders' => array(

                'allborders' => array(

                    'style' => PHPExcel_Style_Border::BORDER_THIN

                )

            )

        );

        //background

        $styleArray12 = array(

            'fill' => array(

                'type' => PHPExcel_Style_Fill::FILL_SOLID,

                'startcolor' => array(

                    'rgb' => 'FFFF00',

                ),

            ),

        );

        //freeepane

        $object->getActiveSheet()->freezePane('A2');

        //coloum width

        $object->getActiveSheet()->getColumnDimension('A')->setWidth(15);

        $object->getActiveSheet()->getColumnDimension('B')->setWidth(15);

        $object->getActiveSheet()->getColumnDimension('C')->setWidth(15);

        $object->getActiveSheet()->getColumnDimension('D')->setWidth(20);

        $object->getActiveSheet()->getColumnDimension('E')->setWidth(20);

        $object->getActiveSheet()->getColumnDimension('F')->setWidth(12);

        $object->getActiveSheet()->getColumnDimension('G')->setWidth(15);

        $object->getActiveSheet()->getColumnDimension('H')->setWidth(20);

        $object->getActiveSheet()->getColumnDimension('I')->setWidth(20);

        $object->getActiveSheet()->getColumnDimension('J')->setWidth(20);

        $object->getActiveSheet()->getColumnDimension('K')->setWidth(20);

        $object->getActiveSheet()->getColumnDimension('L')->setWidth(10);

        $object->getActiveSheet()->getColumnDimension('M')->setWidth(12);

        $object->getActiveSheet()->getColumnDimension('N')->setWidth(25);

        $object->getActiveSheet()->getColumnDimension('O')->setWidth(15);

        $object->getActiveSheet()->getColumnDimension('P')->setWidth(15);

        $object->getActiveSheet()->getColumnDimension('Q')->setWidth(15);

        $object->getActiveSheet()->getColumnDimension('R')->setWidth(15);

        $object->getActiveSheet()->getColumnDimension('S')->setWidth(15);

        $object->getActiveSheet()->getColumnDimension('T')->setWidth(25);

        $object->getActiveSheet()->getColumnDimension('U')->setWidth(15);

        $object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray1);

        $object->getActiveSheet()->getStyle('A1:U1')->applyFromArray($styleArray12);

        $object->getActiveSheet()->getStyle('I')->getNumberFormat()->setFormatCode("0.00");    

        $table_columns = array("SRL", "Scheme", "Tran Type", "App Refer", "OTH Refer",

             "Account", "Name", "Value Date", "Amount", "Pay Category", "Rev Flg",

              "Security", "Cheque Number", "SCH", "Book Date", "Cheque Date", 

              "Reg Id", "Inputter", "Narration", "FL", "Batch Number");

            $column = 0;

            foreach($table_columns as $field)
            {
                $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
                $column++;
            } 


        }

        if($glnames == 'gl2') {

            //style alignment

            $styleArray = array(

                'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,

                    'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,

                ),

            );

            $object->getActiveSheet()->getStyle('A1:C1')->getFont()->setBold(true);

            $object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray);

            //border

            $styleArray1 = array(

                'borders' => array(

                    'allborders' => array(

                        'style' => PHPExcel_Style_Border::BORDER_THIN

                    )

                )

            );

            //background

            $styleArray12 = array(

                'fill' => array(

                    'type' => PHPExcel_Style_Fill::FILL_SOLID,

                    'startcolor' => array(

                        'rgb' => 'FFFF00',

                    ),

                ),

            );

            //freeepane

            $object->getActiveSheet()->freezePane('A2');

            //coloum width

            $object->getActiveSheet()->getColumnDimension('A')->setWidth(15);

            $object->getActiveSheet()->getColumnDimension('B')->setWidth(15);

            $object->getActiveSheet()->getColumnDimension('C')->setWidth(15);

            $object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray1);

            $object->getActiveSheet()->getStyle('A1:C1')->applyFromArray($styleArray12);

            $object->getActiveSheet()->getStyle('C')->getNumberFormat()->setFormatCode("0.00");

            $table_columns1 = array("Account", "Name", "Amount");

            $column1 = 0;

            foreach($table_columns1 as $field1)
            {
                $object->getActiveSheet()->setCellValueByColumnAndRow($column1, 1, $field1);
                $column1++;
            } 

        }

        // List of column names

        

        $style = array(

                'alignment' => array(

                    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,

                )
        );

        $prestasi->getDefaultStyle()->applyFromArray($style);

        if($glnames == 'gl1') {
              // Gl1 Query
             $excel_row = 2;
             for ($kk=0;$kk<count($account_number);$kk++) 
             { 
                $account_number2 = $account_number[$kk];
              $gl1Arr = $this->ut_gl_model->getDisplayGl1Query($account_number2,$from_date1,$to_date1);

              foreach($gl1Arr as $row)
              {           

               $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row, $row['srl']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row['scheme']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row['tran_type']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row['app_refer']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row['oth_refer']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $row['account']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $row['name']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, (isset($row['value_date']) && $row['value_date']!='0000-00-00')?date('d/m/Y',strtotime($row['value_date'])):'');
               $object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $row['amt']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(9, $excel_row, $row['pay_catego']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(10, $excel_row, $row['rev_flg']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(11, $excel_row, $row['security']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(12, $excel_row, $row['chq_number']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(13, $excel_row, 'y');
               $object->getActiveSheet()->setCellValueByColumnAndRow(14, $excel_row, (isset($row['book_date']) && $row['book_date']!='0000-00-00')?date('d/m/Y',strtotime($row['book_date'])):'');
               $object->getActiveSheet()->setCellValueByColumnAndRow(15, $excel_row, (isset($row['chq_date']) && $row['chq_date']!='0000-00-00')?date('d/m/Y',strtotime($row['chq_date'])):'');
               $object->getActiveSheet()->setCellValueByColumnAndRow(16, $excel_row, $row['reg_id']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(17, $excel_row, $row['inputter']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(18, $excel_row, $row['narration']);
               $object->getActiveSheet()->setCellValueByColumnAndRow(19, $excel_row, '');
               $object->getActiveSheet()->setCellValueByColumnAndRow(20, $excel_row, '');
            
               $excel_row++;
          
               } 
               
             }

              // Excel Download Logic
                $downloadFile = 'gl1_'.date('Ymd').'.xlsx';
                $prestasi->setTitle("Gl1 Dump"); 
                $object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel2007');
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="'.$downloadFile.'" ');
                $object_writer->save('php://output');                  
            }

        $excel_row1 = 2;
        if($glnames == 'gl2') {
              // Gl2 Query
            for ($jj=0;$jj<count($account_number);$jj++) 
            { 
                $account_number3 = $account_number[$jj];
                $gl2Arr = $this->ut_gl_model->getDisplayGl2Query($account_number3,$from_date1,$to_date1);

                foreach($gl2Arr as $row1)
                {      
                   $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row1, $row1['account']);
                   $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row1, $row1['name']);
                   $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row1, $row1['amount']);
                   // $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row1, $row1['value_date']);
                   $excel_row1++;
              
                }
            }                   
                // Excel Download Logic
                $prestasi->setTitle("Gl2 Dump");
                $downloadFile2 = 'gl2_'.date('Ymd').'.xlsx'; 
                $object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel2007');
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="'.$downloadFile2.'" ');
                $object_writer->save('php://output');
            }             

    }
    else
    {
        $this->session->set_flashdata('error', 'Data not found.');
        redirect(site_url('sbi-reco/run-gl'));
    }
    

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM