Moodle filesystem is powerful but it's hard to understand too. In this code we will see how to create an excel file and save it in the moodle filesystem:
Documentation:
https://docs.moodle.org/dev/File_API_internals
https://docs.moodle.org/dev/File_API
// Create excel file
require_once("$CFG->libdir/phpexcel/PHPExcel.php");
$filenameTmp = tempnam(sys_get_temp_dir(), time());
$objPHPExcel = new PHPExcel();
// Excel metadata
$objPHPExcel->getProperties()->setCreator("www.ibancardonasubiela.tk")
->setLastModifiedBy("www.ibancardonasubiela.tk")
->setTitle("www.ibancardonasubiela.tk")
->setSubject("www.ibancardonasubiela.tk")
->setDescription("www.ibancardonasubiela.tk")
// Crear the first sheet
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle("www.ibancardonasubiela.tk");
// Header
$arrayHeader = array('aaa', 'bbb');
$countHeader = count($arrayHeader);
foreach ($arrayHeader as $pos => $value) {
$excelLetter = PHPExcel_Cell::stringFromColumnIndex($pos);
$objPHPExcel->getActiveSheet()->getStyle($excelLetter.'1')->getFont()->setSize(14);
$objPHPExcel->getActiveSheet()->getStyle($excelLetter.'1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->setCellValue($excelLetter.'1', $value);
$objPHPExcel->getActiveSheet()->getColumnDimension($excelLetter)->setAutoSize(true);
}
// Add content
// Save excel in a temporal file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($filenameTmp);
// Copy excel to moodle filesystem
$fs = get_file_storage();
$file_record = array(
'contextid' => 0,
'component' => 'backup', // "mod_forum", "course", "mod_assignment", "backup"...
'filearea' => 'course', // "submissions", "intro" and "content" , "blogs","userfiles"...
'itemid' => 0,
'filepath' => '/',
'timecreated' => time(),
'timemodified' => time(),
'filename' => 'excel'.'_'.time().'.xlsx'
);
$fs->create_file_from_pathname($file_record, $filenameTmp);
// Delete temp file
unlink($filenameTmp);
Best regards!