Search code examples
phpformattingxlsxexport-to-html

PHP thousand separator formatting for generated page from xlsx


Ty mail2bapi, :)

Im using SimpleXLSX and example script below in code i added this $x = number_format($r);

Just need the numbers to have thousand separator 252252732 to 252,252,732

IM not good with PHP, really appreciate any help

Plus some columns are empty and dates like so 23.01.2020, I think this is what is causing the issue

XMLS File simplexlsx

Error: number_format() expects parameter 1 to be double, array given in

Error: implode(): Invalid arguments passed

<?php
require_once 'SimpleXLSX.php';

if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
    echo '<table border="1" cellpadding="3" style="border-collapse: collapse">';
    foreach( $xlsx->rows() as $r ) {
        $x = number_format($r);
        echo '<tr><td>'.implode('</td><td>', $x ).'</td></tr>';
    }
    echo '</table>';
    // or $xlsx->toHTML();  
} else {
    echo SimpleXLSX::parseError();
}

?>

Solution

  • You are not using number_format() function correctly. Change following code from -

    $x = number_format($r);
    

    to

    $x = number_format($r, 0, ".", ",");
    

    for more information visit PHP number_format

    EDIT

    As you mentioned your row could have a different type of values, it is better to check the value for numeric.

    Try this code

    <?php
    require_once 'SimpleXLSX.php';
    
    if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
         echo '<table border="1" cellpadding="3" style="border-collapse: collapse">';
        foreach( $xlsx->rows() as $rowValue ) {
           echo "<tr>";
           // As $rowValue is an array  
           foreach($rowValue as $value){
              // Check for number_format
              if(is_numeric($value)){
                $x = number_format($value, 0, ".", ",");
                echo "<td>".$x."</td>";
              }else{
                echo "<td>".$value."</td>";
              }
           }
           echo "</tr>";  
        }
        echo "</table>";
    
        // or $xlsx->toHTML();  
    } else {
        echo SimpleXLSX::parseError();
    }
    

    Hope these resolve your issue.