如何阅读XLS文件&将其转换为CSV格式

时间:2016-10-13 04:25:19

标签: php excel csv customization

我在XLS文件的第1列中有以下数据

<table border="1">
<tr>
    <th align="left">First Name</th>
    <th align="left">Gender</th>
    <th align="left">Nationality</th>
</tr>
<tr>
    <td align="left">Mike</td>
    <td align="left">M</td>
    <td align="left">Singaporean</td>
</tr>

我想将其转换为CSV文件,因此输出应为CSV文件

First Name Gender Nationality
Mike       M      Singaporean

我听到了https://sourceforge.net/projects/phpexcelreader/

如何使用自定义PHP脚本实现?

1 个答案:

答案 0 :(得分:0)

从xls文件中获取数据 - $ dataArray 我刚刚介绍了导出功能

在控制器

/** Function that is used to do export functionality
 *
 * @return Response
 */
public function exportAction(Request $request)
{
    $delimiter = '';

    if ($request->getMethod() == 'POST') {
        /* Form values */
        $csvType = $request->request->get('CSVtype');

        /* setting the CSV type delimiter */
        $delimiter = ($csvType == "colonSep") ? ";" : ",";
        /* Ends here */

    }

    $response = $this->createCsvfile($dataArray, $columnNames, $delimiter);

    return $response;
}

/**
 * Function that is used to generate csv data
 *
 * @param Array   $dataArray   Data array
 * @param Strings $columnNames Column names
 * @param Int     $delimiter   Delimiter

 *
 * @return String
 */
private function generateCsv($dataArray, $columnNames, $delimiter)
{
    $delimiter = '"' . $delimiter . '"';

    $content = '"' . implode($delimiter, str_replace('"', '', $columnNames)) . '"';
    $content .= "\n";
    foreach ($dataArray as $value) {
       $content .= '"' . implode($delimiter, str_replace('"', '', $value)) . '"' . "\n";
    }

    return $content;
}



/**
 * To create csv file
 * @param array  $finalResultArray selected  club      data
 * @param array  $columnNames      selected  columns
 * @param String $delimiter        delimiter

 *
 * @return \Symfony\Component\HttpFoundation\Response
 */
private function createCsvfile($finalResultArray, $columnNames, $delimiter)
{

    $filename = 'export_' . date("Y-m-d") . '_' . date("H-i-s") . '.csv';
    $response = new Response();
    // prints the HTTP headers followed by the content
    $response->setContent(utf8_decode($this->generateCsv($finalResultArray, $columnNames, $delimiter)));
    $response->setStatusCode(200);
    $response->headers->set('Content-Type', 'application/csv; charset=utf-8');
    $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
    $response->headers->set('Content-Transfer-Encoding', 'binary');

    return $response;
}