将xlsx转换为csv无法在服务器上运行

时间:2017-02-14 12:52:09

标签: php phpexcel

我想将xlsx文件中的数据导入到我的数据库中,我使用的phpexcel库将xls或xlsx文件转换为csv,然后读取数据。 此代码正常工作以将xls文件转换为本地主机和服务器上的csv,但xlsx到csv转换仅在本地主机上完成。 这是我的代码:

function convertXLStoCSV($infile,$outfile)
{

$fileType = PHPExcel_IOFactory::identify($infile);

$objReader = PHPExcel_IOFactory::createReader($fileType);

$objReader->setReadDataOnly(true);   
$objPHPExcel = $objReader->load($infile);    

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($outfile);


 }

并使用以下方法调用此函数:

if($ext == 'xls' or $ext == 'xlsx')
{

     $new_doc_name = time() . "." .$ext; 

    $target_path = "../../uploaded_files/";
    $target_path = $target_path . $new_doc_name ; 

        if ($_FILES["CSV_file"]["type"] == "application/xls" or $_FILES["CSV_file"]["type"] == "application/xlsx" or $_FILES["CSV_file"]["type"] == "application/vnd.ms-excel" or $_FILES["CSV_file"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){

        if(move_uploaded_file($_FILES['CSV_file']['tmp_name'], $target_path)) {


        convertXLStoCSV($target_path,'output.csv');
       if(($handle = fopen("output.csv" , "r")) !== FALSE) 

请帮助

1 个答案:

答案 0 :(得分:2)

试试这个

$objReader = PHPExcel_IOFactory::createReader('Excel2007');
    $objPHPExcel = $objReader->load($uploadFIle);

    $objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
    $highestRow = $objWorksheet->getHighestRow();
    $highestColumn = $objWorksheet->getHighestColumn();

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');    
 $index = 0;
    foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {

        $objPHPExcel->setActiveSheetIndex($index);

        // write out each worksheet to it's name with CSV extension
        $outFile = str_replace(array("-"," "), "_", $worksheet->getTitle()) .".csv";

        $objWriter->setSheetIndex($index);
        $objWriter->save($outFile);

        $index++;
    }