转载:Create and Read Excel File using PHP - TrinityTuts
In this post I will explain to you how we can create and read Excel (.xlsx||.xls) using PHP. If you miss my last post in which I explain how to create a CSV file using PHP please read that post. For this post, I am using PhpSpreadsheet plugin. You can use this plugin in any framework you can install this plugin using composer.
// ADD DATA TO SPECIFIC CELL $spreadsheet->getActiveSheet()->setCellValue('A1', 'Hello World !');
// Create a new worksheet called "My Data" // Attach the "My Data" worksheet as the first worksheet in the Spreadsheet object $myWorkSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'My Data'); $spreadsheet->addSheet($myWorkSheet, 0);
// Create Excel file and sve in your directory $writer = new Xlsx($spreadsheet); $writer->save('mysheet.xlsx');
Step 5. Now if you want to array data in your excel at location use below code
$arrayData = [ ['Aneh', 'Amit', 'Ajay', 'Sanjeev'], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ]; $spreadsheet->getActiveSheet() ->fromArray( $arrayData, // The data to set NULL, // Array values with this value will not be set 'A1'// Top left coordinate of the worksheet range where );
// Create Excel file and sve in your directory $writer = new Xlsx($spreadsheet); $writer->save('mysheet.xlsx');
Step 6. Now if you want to create a fixed header in your excel sheet. We use freezePane method to fixed header
$arrayData = [ ['Aneh', 'Amit', 'Ajay', 'Sanjeev'], ['Q1', 12, 15, 21], ['Q2', 56, 73, 86], ]; $spreadsheet->getActiveSheet() ->fromArray( $arrayData, // The data to set NULL, // Array values with this value will not be set 'A1'// Top left coordinate of the worksheet range where );
// Create Excel file and sve in your directory $writer = new Xlsx($spreadsheet); $writer->save('mysheet.xlsx');
/** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Advise the Reader that we only want to load cell data **/ $reader->setReadDataOnly(true);
/** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Advise the Reader that we only want to load cell data **/ $reader->setReadDataOnly(true);
/** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Advise the Reader that we only want to load cell data **/ $reader->setReadDataOnly(true);