PHP Excel Upload ve Exel İndirme
PHP- Kodu:
<?php namespace ProjectControllers;
use PHPExcel, PHPExcel_IOFactory, PHPExcel_Reader_Excel2007;
class ExcelSample extends Controller
{
public function download()
{
$objPHPExcel = new PHPExcel();
// Rename worksheet // Çalışma sayfasının adı
$objPHPExcel->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'T.C Kimlik No');
$objPHPExcel->getActiveSheet()->setCellValue('B1', 'Adı');
$objPHPExcel->getActiveSheet()->setCellValue('C1', 'Soyadı');
$objPHPExcel->getActiveSheet()->setCellValue('D1', 'E-posta');
$row_index = 2;
for ($i = 1; $i <= 10; $i++) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $row_index, 'T.C Kimlik ' . $i);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, $row_index, 'Adı ' . $i);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, $row_index, 'Soyadı ' . $i);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, $row_index, 'E-posta' . $i);
$row_index++;
}
foreach (range('A1', 'D1') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
//Set Save File Name
$file_name = 'List' . date('Ymd_Hi') . '.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $file_name . '"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
}
public function read()
{
$file = RESOURCES_DIR . 'Filesexample2.xlsx';
$data = [];
$phpExcelReader = new PHPExcel_Reader_Excel2007();
$phpExcelReader->setReadDataOnly(true);
$phpExcel = $phpExcelReader->load($file);
$phpExcel->setActiveSheetIndex(0);
$row_count = $phpExcel->getActiveSheet()->getHighestRow();
for ($row_index = 2; $row_index <= $row_count; $row_index++) {
$number = trim($phpExcel->getActiveSheet()->getCell('A' . $row_index)->getValue());
$name = trim($phpExcel->getActiveSheet()->getCell('B' . $row_index)->getValue());
$surname = trim($phpExcel->getActiveSheet()->getCell('C' . $row_index)->getValue());
$email = trim($phpExcel->getActiveSheet()->getCell('D' . $row_index)->getValue());
$data[] = [
'identity_number' => $number,
'name' => $name,
'surname' => $surname,
'email' => $email,
];
}
output($data);
// Add to the database // Veritabanına eklemek için
foreach ($data as $key => $value) {
DB::insert('table',
[
'identity_number' => $value['identity_number'],
'name' => $value['name'],
'surname' => $value['surname'],
'email' => $value['email'],
]);
}
}}