简体   繁体   中英

Export Table as Excel file in php

CSS is effecting in UI but not in Excel. Anyone can help me on this please.

Below code will export table into excel but not able to provide space before tags.

<?php 
    echo $excel_data = '<table border="1">
        <thead>
            <th align="left">S.No.</th>
            <th align="left">Name</th>
            <th align="left">DOJ</th>
        </thead>
        <tbody>
            <tr>
                <td align="left">1</td>
                <td align="left">Sreekanth Kuriyala</td>
                <td align="left">04-06-2015</td>
            </tr>
            <tr>
                <td align="left">2</td>
                <td style="padding-left:20px;">SK</td>
                <td align="left">26-07-2015</td>
            </tr>
        </tbody>
    </table>';
    $excel_file = 'Reports.xls';
    file_put_contents ($excel_file, $excel_data);
?>
</br>
</br>
<a href="<?php echo $excel_file; ?>" download>Export to Excel</a>   

you have to create a CSV file just create new php file with a function that expects a result of a db select.

then just echo cols separated by ; and carrier return for next row.

this is a function i made:

<?php
function printcsv($result){
                  //result of database select 
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename=example.csv');
echo "\xEF\xBB\xBF";
$nl = "\n";
//this will be the carrier return var
    if($rs = $result->fetch_array(MYSQLI_NUM)){
        while($rs != ''){
            echo $rs[0].";".$rs[1].";".$rs[2].";".$rs[3].";".$rs[4].";".$rs[5].";".$nl;
            $rs = $result->fetch_array(MYSQLI_NUM);
        }
    }
}
?>

change my mysqli_fetch_array by your result desired fetch and try it =)

oh, and you cannot write tables on it, only echo data separated by semicolon. each data for each column, semicolon to put the next data in next column, and carrier return to write in next row.

cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM