简体   繁体   中英

PHP Convert Excel File From “.xls” To “.xlsx”

im working in a php project in witch i have to send a mail with an excel attachment , for the mail im using phpmailer . Im having a problem with the format of the excel file that the code below produces.

$table.='<table></table>';
    if (file_exists("EXCEL REPORT/".$subject." ".date("M-d-Y").".xls")) 
    {
        unlink("EXCEL REPORT/".$subject." ".date("M-d-Y").".xls");
        file_put_contents("EXCEL REPORT/".$subject." ".date("M-d-Y").".xls", $table); 
        sendmailatt($to,$cc,$subject." ".date("M-d-Y"),"mail",<br>REGIA","EXCEL REPORT/".$subject." ".date("M-d-Y").".xls");
    } 
    else {
       file_put_contents("EXCEL REPORT/".$subject." ".date("M-d-Y").".xls", $table); 
       sendmailatt($to,$cc,$subject." ".date("M-d-Y"),"Questo e' un invio automatico del venduto per agent.<br><br>Saluti,<br>REGIA","EXCEL REPORT/".$subject." ".date("M-d-Y").".xls");
    }

i want to convert the attachment into excel 2007 before sending the mail... is there any easy way for achieving this

There is PHPExcel . You can find the documentation for reading and writing files here .

EDIT: turns out PHPExcel is deprecated, the project recommends PhpOffice/PphSpreadsheet , you can find details on how to read and write here .

Here is a code example of converting from .xls to .xlsx using PHPExcel (it might be deprecated, but it still works just fine, especially for a simple conversion of Excel5 to Excel2007):

<?php

    $xls_to_convert = 'test.xls';

    //------------------------------------------------------------------------------------

    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

    //These four lines are the entire script
    require_once dirname(__FILE__) . '/PHPExcel/Classes/PHPExcel/IOFactory.php';
    $objPHPExcel = PHPExcel_IOFactory::load(dirname(__FILE__) . '/' . $xls_to_convert);
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save(str_replace('.xls', '.xlsx', $xls_to_convert));

    echo 'File ' . str_replace('.xls', '.xlsx', $xls_to_convert) . ' created in ' , getcwd() , EOL;

The above example assumes:

1) PHPExcel is installed into your web files folder (eg home/username/public_html , xampp/htdocs , var/www , etc)

2) test.xls is also located in the same folder

3) Tested with the latest (final) version of PHPExcel, 1.8

4) The code is taken from PHPExcel/Examples/07reader.php

Many thanks to Mark Baker for the PHPExcel and PhpSpreadsheet applications!

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