Home Backend Development PHP Problem How to convert csv to xls in php

How to convert csv to xls in php

Mar 20, 2023 pm 03:35 PM
php csv xls

During the actual development process, we may need to convert data in CSV format into Excel format (XLS or XLSX). Because the CSV file is just a simple text file, and the Excel file supports more functions, such as data filtering, sorting, chart display, etc. PHP provides a powerful function library for processing CSV and Excel. The following will introduce how to use PHP to convert CSV files into Excel files.

  1. Read CSV file

PHP provides the fgetcsv() function for reading CSV files and parsing each line into an array . The following is an example of reading a CSV file:

$csvFile = 'data.csv';
if(!file_exists($csvFile)) {
    die("File not found");
}
$fp = fopen($csvFile, 'r');
if(!$fp) {
    die("Error opening file");
}
$data = array();
while($row = fgetcsv($fp)) {
    $data[] = $row;
}
fclose($fp);
Copy after login

This code first checks whether the CSV file exists, then opens the file, and uses the fgetcsv() function to read each line of the file and stores the result in an array middle.

  1. Create Excel files

PHPExcel is a very powerful PHP extension for creating and manipulating Excel files. We can download PHPExcel and include it into our PHP project. The method to create an empty Excel file is as follows:

require_once 'PHPExcel.php';

$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Sheet1');
Copy after login

This code uses PHPExcel to create an empty Excel file and sets a default worksheet.

  1. Import CSV data into an Excel file

Using the setCellValue() method in PHPExcel, we can import the data in the CSV file into an Excel file. The following is a sample code:

require_once 'PHPExcel.php';

$csvFile = 'data.csv';
if(!file_exists($csvFile)) {
    die("File not found");
}
$csvData = file_get_contents($csvFile);
$data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $csvData));

$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Sheet1');

$row = 1;
foreach($data as $fields) {
    $col = 0;
    foreach($fields as $value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}
Copy after login

This code first uses the file_get_contents() function to read the contents of the CSV file, and then uses the preg_split() function to split the file contents into a two-dimensional array. Next, we use PHPExcel’s setCellValueByColumnAndRow() function to import the data into the Excel file.

  1. Save the Excel file

Finally, we use PHPExcel’s save() method to save the file in XLS or XLSX format. The following is the complete sample code:

require_once 'PHPExcel.php';

$csvFile = 'data.csv';
if(!file_exists($csvFile)) {
    die("File not found");
}
$csvData = file_get_contents($csvFile);
$data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $csvData));

$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Sheet1');

$row = 1;
foreach($data as $fields) {
    $col = 0;
    foreach($fields as $value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('data.xls');
Copy after login

This code imports data into a PHPExcel object and uses the createWriter() method of PHPExcel_IOFactory to generate an Excel5Writer object for saving the PHPExcel object as a file in XLS format. It should be noted that in order to use Excel2007 format (XLSX), you need to change Excel5 to Excel2007.

Summary

The above is the complete process of converting CSV files into Excel files. First read the CSV file, then import the data into a PHPExcel object and save the PHPExcel object as an Excel file. It should be noted that in actual applications, we may need to perform format verification and cleaning on the imported data to ensure the integrity and correctness of the data.

The above is the detailed content of How to convert csv to xls in php. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

CakePHP Date and Time

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

CakePHP File upload

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

CakePHP Routing

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

CakePHP Project Configuration

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

Discuss CakePHP

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP Quick Guide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

How To Set Up Visual Studio Code (VS Code) for PHP Development

See all articles