Skip to content

Instantly share code, notes, and snippets.

@r-sal
Last active May 26, 2025 08:41
Show Gist options
  • Select an option

  • Save r-sal/4313500 to your computer and use it in GitHub Desktop.

Select an option

Save r-sal/4313500 to your computer and use it in GitHub Desktop.
PHPExcel Notes and code snippets

Basics

Creating a new PHPExcel Object.

$this->PHPExcel = new PHPExcel();

Sheets

A new sheet can be added to the excel file using:
$this->activeSheet = $this->PHPExcel->createSheet();
and the sheet title can be set or renamed using:
$this->activeSheet->setTitle($title);

Getting the active sheet:
$this->activeSheet = $this->PHPExcel->getActiveSheet();

Setting the active sheet:

$sheetIndex = 2;
$this->PHPExcel->setActiveSheetIndex($sheetIndex)

Setting the width of a specific column.

$this->activeSheet
    ->getColumnDimension($colString)
    ->setWidth($width);

Setting the default column width/row height for an entire sheet.

$this->activeSheet
    ->getDefaultColumnDimension()
    ->setWidth($width);
    
$this->activeSheet
    ->getDefaultRowDimension()
    ->setRowHeight($height);

Styles

Setting default styles for the active sheet

$this->activeSheet
    ->getDefaultStyle()
    ->applyFromArray($this->defaultStyle);

Writing to cells

Text can be added to a cell using setCellValue($colRow, $data)
$colRow - The column and row to write to (i.e. 'A2')
$data - The data to write

    $this->activeSheet->setCellValue($colRow, $data);       
    $this->activeSheet->setCellValueByColumnAndRow($column, $row, $data);  
    $this->activeSheet->setCellValueExplicit($coord, $value, $dataType);  
    $this->activeSheet->setCellValueExplicitByColumnAndRow($col, $row, $value, $dataType);  

Writing from arrays

A 2-dimensional array can be written to the current sheet usng fromArray($twoDimArray)

  • $twoDimArray - the 2D array to be written
  • $useWhenNull - what to use if there is a null value
  • $topLeftCorner - where the top left corner should be.
$this->activeSheet->fromArray($sheet);  
$this->activeSheet->fromArray($sheet, "", $colRow);  

Or the array can be written manually by looping through the array and calling setCellValue

foreach($rows as $row => $columns) {
    foreach($columns as $column => $data) {
        $this->activeSheet->setCellValue($column.$row, $data);
    }
}
@manvendrasinghbhati
Copy link

nice

@manvendrasinghbhati
Copy link

" . mysql_error () . "
" . mysql_errno () ); // select database $Db = @mysql_select_db ( $dbname, $Connect ) or die ( "Couldn't select database:
" . mysql_error () . "
" . mysql_errno () ); // execute query $result = @mysql_query ( $sql_qry, $Connect ) or die ( "Couldn't execute query:
" . mysql_error () . "
" . 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 ); $styleArrayHeaderTab = array ( 'font' => array ( 'bold' => true, 'color' => array ( 'rgb' => 'FFFFFF' ), 'size' => 11, 'name' => 'Arial' ), 'fill' => array ( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array ( 'rgb' => 'FF0000' ) ), 'alignment' => array ( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT ) ); $styleArrayHeader = array ( 'font' => array ( 'bold' => true, 'color' => array ( 'rgb' => 'FF0000' ), 'size' => 11, 'name' => 'Arial' ), 'alignment' => array ( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_GENERAL ) ); $styleArrayTextDate = array ( 'font' => array ( 'bold' => false, 'color' => array ( 'rgb' => '000000' ), 'size' => 11, 'name' => 'Arial' ), 'alignment' => array ( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT ) ); $styleArrayTextName = array ( 'font' => array ( 'bold' => false, 'color' => array ( 'rgb' => '000000' ), 'size' => 11, 'name' => 'Arial' ), 'alignment' => array ( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT ) ); $styleArrayBodyValue = array ( 'font' => array ( 'bold' => false, 'color' => array ( 'rgb' => '000000' ), 'size' => 10, 'name' => 'Arial' ), 'alignment' => array ( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT ) ); $styleArrayBodyText = array ( 'font' => array ( 'bold' => false, 'color' => array ( 'rgb' => '000000' ), 'size' => 10, 'name' => 'Arial' ), 'alignment' => array ( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT ) ); // start Excel $rowCount = 1; // first rew $column = 'A'; // first column $column_name = array ( "Date", "party name", "Bill no", "item", "Total 5% & 14.5% separate including tax", "Postage", "Sale 5%", "Vat 5%", "Sale 14.5 %", "Vat 14.5%" ); for($i = 0; $i < count ( $column_name ); $i ++) { $objPHPExcel->getActiveSheet ()->setCellValue ( $column . $rowCount, $column_name [$i] ); $objPHPExcel->getActiveSheet ()->getStyle ( $column . $rowCount )->applyFromArray ( $styleArrayHeaderTab ); $column ++; } $Column_Name_Array = array ( "bill_date", "name", "sales_invoice_id", "item", "amount_before_tax5", "freight_postage_charges", "amount_before_tax5", "tax_5", "amount_before_tax14", "tax_14" ); $rowCount = 2; while ( $row = mysql_fetch_array ( $result ) ) { $column = 'A'; for($j = 0; $j < count ( $Column_Name_Array ); $j ++) { if (! isset ( $row [bill_date] )) { $value = NULL; } elseif ($row [bill_date] != "") { $value = strip_tags ( $row [bill_date] ); } else { $value = ""; } $value = trim ( $value ); $objPHPExcel->getActiveSheet ()->setCellValue ( $column . $rowCount, $value ); $objPHPExcel->getActiveSheet ()->getStyle ( $column . $rowCount )->applyFromArray ( $styleArrayTextDate ); } $column = 'B'; for($j = 0; $j < count ( $Column_Name_Array ); $j ++) { if (! isset ( $row [name] )) { $value = NULL; } elseif ($row [name] != "") { $value = strip_tags ( $row [name] . ',' . $row [city] ); } else { $value = ""; } $value = trim ( $value ); $objPHPExcel->getActiveSheet ()->setCellValue ( $column . $rowCount, $value ); $objPHPExcel->getActiveSheet ()->getStyle ( $column . $rowCount )-> applyFromArray ( $styleArrayTextName ); // $column ++; } $column = 'C'; for($j = 0; $j < count ( $Column_Name_Array ); $j ++) { if (! isset ( $row [sales_invoice_id] )) { $value = NULL; } elseif ($row [sales_invoice_id] != "") { $value = strip_tags ( $row [sales_invoice_id] ); } else { $value = ""; } $value = trim ( $value ); $objPHPExcel->getActiveSheet ()->setCellValue ( $column . $rowCount, $value ); $objPHPExcel->getActiveSheet ()->getStyle ( $column . $rowCount )->applyFromArray ( $styleArrayBodyValue ); } $column = 'F'; for($j = 0; $j < count ( $Column_Name_Array ); $j ++) { if (! isset ( $row [freight_postage_charges] )) { $value = NULL; } elseif ($row [freight_postage_charges] != "") { $value = strip_tags ( $row [freight_postage_charges] ); } else { $value = "0"; } $value = trim ( $value ); $objPHPExcel->getActiveSheet ()->setCellValue ( $column . $rowCount, $value ); $objPHPExcel->getActiveSheet ()->getStyle ( $column . $rowCount )->applyFromArray ( $styleArrayBodyValue ); } $column = 'G'; for($j = 0; $j < count ( $Column_Name_Array ); $j ++) { if (! isset ( $row [amount_before_tax5] )) { $value = NULL; } elseif ($row [amount_before_tax5] != "") { $value = strip_tags ( $row [amount_before_tax5] ); } else { $value = "0"; } $value = trim ( $value ); $objPHPExcel->getActiveSheet ()->setCellValue ( $column . $rowCount, $value ); $objPHPExcel->getActiveSheet ()->getStyle ( $column . $rowCount )->applyFromArray ( $styleArrayBodyValue ); } $column = 'H'; for($j = 0; $j < count ( $Column_Name_Array ); $j ++) { if (! isset ( $row [tax_5] )) { $value = NULL; } elseif ($row [tax_5] != "") { $value = strip_tags ( $row [tax_5] ); } else { $value = "0"; } $value = trim ( $value ); $objPHPExcel->getActiveSheet ()->setCellValue ( $column . $rowCount, $value ); $objPHPExcel->getActiveSheet ()->getStyle ( $column . $rowCount )->applyFromArray ( $styleArrayBodyValue ); } $column = 'I'; for($j = 0; $j < count ( $Column_Name_Array ); $j ++) { if (! isset ( $row [amount_before_tax14] )) { $value = NULL; } elseif ($row [amount_before_tax14] != "") { $value = strip_tags ( $row [amount_before_tax14] ); } else { $value = "0"; } $value = trim ( $value ); $objPHPExcel->getActiveSheet ()->setCellValue ( $column . $rowCount, $value ); $objPHPExcel->getActiveSheet ()->getStyle ( $column . $rowCount )->applyFromArray ( $styleArrayBodyValue ); } $column = 'J'; for($j = 0; $j < count ( $Column_Name_Array ); $j ++) { if (! isset ( $row [tax_14] )) { $value = NULL; } elseif ($row [tax_14] != "") { $value = strip_tags ( $row [tax_14] ); } else { $value = ""; } $value = trim ( $value ); $objPHPExcel->getActiveSheet ()->setCellValue ( $column . $rowCount, $value ); $objPHPExcel->getActiveSheet ()->getStyle ( $column . $rowCount )->applyFromArray ( $styleArrayBodyValue ); } $rowCount = $rowCount + 2; } $column = 'D'; $columnItem = 'E'; $rowCountNo = 2; for($j = 1; $j < ($rowCount - 1); $j ++) { if ($rowCountNo % 2 == '1') { $value = 'item 14.5%'; $columnFrist = 'I'; $columnSecond = 'J'; $rowCountNo1 = $rowCountNo - 1; } else { $value = 'item 5%'; $columnFrist = 'G'; $columnSecond = 'H'; $rowCountNo1 = $rowCountNo; } $value = trim ( $value ); $objPHPExcel->getActiveSheet ()->setCellValue ( $column . $rowCountNo, $value ) ->getStyle ( $column . $rowCountNo )->applyFromArray ( $styleArrayBodyText ); ``` $objPHPExcel->getActiveSheet ()->setCellValue ( $columnItem . $rowCountNo, '=SUM(' . $columnFrist . $rowCountNo1 . ':' . $columnSecond . $rowCountNo1 . ')' ); $objPHPExcel->getActiveSheet ()->getStyle ( $columnItem . $rowCountNo )->applyFromArray ( $styleArrayBodyText ); $rowCountNo ++; ``` } //auto size $objPHPExcel->getActiveSheet ()->getColumnDimension ( "A" )->setAutoSize ( true ); $objPHPExcel->getActiveSheet ()->getColumnDimension ( "B" )->setAutoSize ( true ); $objPHPExcel->getActiveSheet ()->getColumnDimension ( "E" )->setAutoSize ( true ); $objPHPExcel->getProperties()->setCreator("Msb") ->setLastModifiedBy("sysquare system") ->setTitle("Office 2007 XLSX Report") ->setSubject("Office 2007 XLSX Report") ->setDescription("Report.") ->setKeywords("office 2007 openxml php") ->setCategory("Report"); 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' );

@Solihin123
Copy link

I have a proble, for sum of column I ,J,K,L.
My code is :<?php

mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');

$tahun = $_POST['tahun'];
/** Error reporting */
error_reporting(E_ALL);

date_default_timezone_set('Asia/Jakarta');

/** Include PHPExcel */
require_once 'Classes/PHPExcel.php';

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

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

// Create the worksheet
$objPHPExcel->setActiveSheetIndex(0);

$objPHPExcel->getActiveSheet()->setCellValue('A4', "NO")
->setCellValue('B4', "SALES")
->setCellValue('C4', "NO.PO")
->setCellValue('D4', "CUSTOMER")
->setCellValue('E4', "NO.INV")
->setCellValue('F4', "DATE")
->setCellValue('G4', "NO.URUT F.PAJAK")
->setCellValue('H4', "FAKTUR PAJAK")
->setCellValue('I4', "DPP")
->setCellValue('J4', "PPN")
->setCellValue('K4', "TOTAL")
->setCellValue('L4', "PPH 23")
->setCellValue('M4', "NET");

include("Includes/db.php");

$SQL =
mysql_query("SELECT no_inv_manual,nm_sales,no_inv,pajak,nm_cust,no_po,no_order,disc1,disc4,faktur_pajak,
sum(hrg_jual * qty_terima_cust) as tot_hrg_jual,Sum(hrg_jual * qty_terima_cust) as tot_jual,
DATE_FORMAT(tgl_po,'%d-%m-%Y') as Xtgl_po,DATE_FORMAT(tgl_inv,'%d-%m-%Y') as Xtgl_inv,DATE_FORMAT(tgl_dn,'%d-%m-%Y') as Xtgl_dn,DATE_FORMAT(tgl_fak_beli,'%d-%m-%Y') as Xtgl_fak_beli from dt_order
where not no_inv = '' AND tgl_inv >= '2016-05-01' and tgl_inv <= '2016-05-21' group by no_inv ");

$totJML = mysql_num_rows($SQL);

$dataArray= array();
$no=0;
while($row = mysql_fetch_array($SQL)){
$no++;

        if(substr($row['faktur_pajak'],0,3) == '070' or substr($row['faktur_pajak'],0,3) == '030' ){
            $Xpajak = 0;
        } else {
            $Xpajak = 10/100 * $row['tot_jual'];
        }

$tot_jual_ppn = $Xpajak + $row['tot_jual'];

        if(substr($row['faktur_pajak'],0,3) == '030'  ){
           $pph_23 = 1.5 / 100 * $row['tot_jual'];    
        } else {
           $pph_23 = 0;
        }      

$tot_net = $tot_jual_ppn - $pph_23;

$row_array['no'] = $no;
$row_array['nm_sales'] = $row['nm_sales'];
$row_array['no_po'] = $row['no_po'];
$row_array['nm_cust'] = $row['nm_cust'];
$row_array['no_inv'] = $row['no_inv'];
$row_array['Xtgl_inv'] = $row['Xtgl_inv'];
$row_array['Xurut'] = substr($row['faktur_pajak'],8);
$row_array['faktur_pajak'] = $row['faktur_pajak'];
$row_array['dpp'] = $row['tot_jual'];
$row_array['ppn'] = number_format($Xpajak);
$row_array['total'] = number_format($tot_jual_ppn);
$row_array['pph_23'] = number_format($pph_23);
$row_array['total_net'] = number_format($tot_net);
$row_array['total_all'] = $row['tot_jual'];
array_push($dataArray,$row_array);

}

$nox=$no+4;

// $objPHPExcel->getActiveSheet()->setSharedStyle($sharedStyle1, "A4:M$nox");

/// $objPHPExcel->getActiveSheet()->setCellValue($row_array['total_all'], 'Total excl.:');
$objPHPExcel->getActiveSheet()->setCellValue('I22', '=SUM(I5:I20)');

$objPHPExcel->getActiveSheet()->fromArray($dataArray, NULL, 'A5');

// Set page orientation and size
$objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
$objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_LEGAL);
$objPHPExcel->getActiveSheet()->getPageMargins()->setTop(0.75);
$objPHPExcel->getActiveSheet()->getPageMargins()->setRight(0.75);
$objPHPExcel->getActiveSheet()->getPageMargins()->setLeft(0.75);
$objPHPExcel->getActiveSheet()->getPageMargins()->setBottom(0.75);
$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $objPHPExcel->getProperties()->getTitle() . '&RPage &P of &N');

// Set title row bold;
$objPHPExcel->getActiveSheet()->getStyle('A4:M4')->getFont()->setBold(true);
// Set fills
$objPHPExcel->getActiveSheet()->getStyle('A4:M4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$objPHPExcel->getActiveSheet()->getStyle('A4:M4')->getFill()->getStartColor()->setARGB('FF808080');

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setAutoSize(true);

// Set autofilter
// Always include the complete filter range!
// Excel does support setting only the caption
// row, but that's not a best practise...
//$objPHPExcel->getActiveSheet()->setAutoFilter($objPHPExcel->getActiveSheet()->calculateWorksheetDimension());

// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

$sharedStyle1 = new PHPExcel_Style();
$sharedStyle2 = new PHPExcel_Style();

$sharedStyle1->applyFromArray(
array('borders' => array(
'bottom' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
'top' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
'right' => array('style' => PHPExcel_Style_Border::BORDER_MEDIUM),
'left' => array('style' => PHPExcel_Style_Border::BORDER_MEDIUM)
),
));

$objPHPExcel->getActiveSheet()->setSharedStyle($sharedStyle1, "A4:M$nox");

// Set style for header row using alternative method
$objPHPExcel->getActiveSheet()->getStyle('A4:M4')->applyFromArray(
array(
'font' => array(
'bold' => true
),
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
),
'borders' => array(
'top' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
),
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
'rotation' => 90,
'startcolor' => array(
'argb' => 'FFA0A0A0'
),
'endcolor' => array(
'argb' => 'FFFFFFFF'
)
)
)
);

// Add a drawing to the worksheet
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Logo');
$objDrawing->setDescription('Logo');
$objDrawing->setPath('images/R-3.gif');
$objDrawing->setCoordinates('B2');
$objDrawing->setHeight(50);
$objDrawing->setWidth(50);
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());

$objPHPExcel->getActiveSheet()->getStyle('A4:M1000')->getFont()->setName('Calibri');
$objPHPExcel->getActiveSheet()->getStyle('A4:M1000')->getFont()->setSize(11);

// Merge cells
$objPHPExcel->getActiveSheet()->mergeCells('D2:M2');
$objPHPExcel->getActiveSheet()->setCellValue('D2', "LAPORAN PENJUALAN $tahun");
$objPHPExcel->getActiveSheet()->getStyle('D2:M2')->getFont()->setName('Arial');
$objPHPExcel->getActiveSheet()->getStyle('D2:M2')->getFont()->setSize(18);
$objPHPExcel->getActiveSheet()->getStyle('D2')->getFont()->setSize(22);
$objPHPExcel->getActiveSheet()->getStyle('D2:M2')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="lap.penjualan"'.date("d-F-Y").'".xlsx"');
header('Cache-Control: max-age=0');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;

// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', FILE));
?>

Please help me send answer to my email.

@denism300
Copy link

I have a problem with adding a hyperlink to the sheet.
I do exactly as the manual, but the tooltip can not be inserted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment