【问题标题】:convert an EXCEL file to CSV file in PHP [duplicate]在PHP中将EXCEL文件转换为CSV文件[重复]
【发布时间】:2015-08-20 07:49:29
【问题描述】:

我想使用脚本 PHP 将 Excel 文件 (.xls) 转换为 CSV 文件 (.csv) ? 我尝试了很多代码,但它没有像这个一样工作! 没有出现错误,但它不会工作我可以尝试任何想法或任何其他代码行吗?

<?php

echo("it works");
require_once '../batchs/Classes/PHPExcel/IOFactory.php';

$inputFileType = 'Excel5';
$inputFileName = '../public/aixstream/stock.xls';

$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcelReader = $objReader->load($inputFileName);

$loadedSheetNames = $objPHPExcelReader->getSheetNames();

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');

foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    $objWriter->setSheetIndex($sheetIndex);
    $objWriter->save($loadedSheetName.'.csv');
}
?>

谢谢

【问题讨论】:

  • 你可以尝试改变 $objWriter->save($loadedSheetName.'.csv');到 $objWriter->save('./'.$loadedSheetName.'.csv');看看它是否有效
  • 我改了但是没用!
  • 检查 javascript 控制台,是否显示任何错误
  • 不,根本没有错误!

标签: php csv import-from-excel


【解决方案1】:

正如this 答案中所述,您可以使用PHP-ExcelReader function 来读取xls 文件。之后,您可以使用以下代码轻松将其转换为 CSV(或任何其他格式),也可以使用 here

读取 xls 文件

//You will obviously need to import the function
//by downloading the file from the link above.

$reader=new Spreadsheet_Excel_Reader(); //Instantiate the function
$reader->setUTFEncoder('iconv'); // Set Encoder
$reader->setOutputEncoding('UTF-8'); // Set Output Encoding Type
$reader->read($filename); // Read the xls file

数据输出

/***
* Information about sheets is stored in boundsheets variable.
* This code displays each sheet's name.
***/
foreach ($reader->boundsheets as $k=>$sheet) //Run loop for all sheets in the file
 {
    echo "\n$k: $sheet"; 
 }

//Now just save the data in the array as csv

/***
* Data of the sheets is stored in sheets variable.
* For every sheet, a two dimensional array holding table is created.
* This code saves all data to CSV file.
***/
 foreach($reader->sheets as $k=>$data) // Run loop for all items.
 {
    echo "\n\n ".$reader->boundsheets[$k]."\n\n"; //Print Title

    foreach($data['cells'] as $row) // Loop for all items
    {
        foreach($row as $cell) // Loop for every cell
        {
            echo "$cell".","; //Add a comma after each value
        }
    }
 }

//It works! :D

【讨论】:

  • 你能给我解释一下代码吗?您会在下面找到我的答案和代码,因为评论太长了
  • 是的,当我查看下面的代码时,它看起来还不错,尽管我没有通过运行它来检查它。你试过运行它吗?不要忘记,您需要在答案中包含我提供链接的功能才能正常工作。我已经编辑了我的答案,包括解释代码如何工作的 cmets。正如我已经说过的,详细的解释也可以在in this link 获得。
猜你喜欢
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 2021-12-22
相关资源
最近更新 更多