728x90
반응형
1. phpspreadsheet 설치
composer require phpoffice/phpspreadsheet
2. 라이브러리 추가(코드이그나이터)
- apllication/libraries에 Spreadsheet.php를 추가 (그대로 복붙!)
if (!defined('BASEPATH')) exit('No direct script access allowed');
// Composer autoload 포함
require_once APPPATH . '../vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet as PhpSpreadsheetObj; // 이름 충돌 방지
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
class Spreadsheet {
// 엑셀 파일 읽기 (CSV 한글 대응 포함)
public function readExcel($file_path)
{
$reader = IOFactory::createReaderForFile($file_path);
// CSV 파일일 경우 인코딩 + 구분자 설정
if ($reader instanceof \PhpOffice\PhpSpreadsheet\Reader\Csv) {
$reader->setInputEncoding('EUC-KR');
$reader->setDelimiter("\t");
$reader->setEnclosure('"');
}
$spreadsheet = $reader->load($file_path);
return $spreadsheet->getSheet(0)->toArray(null, true, true, true);
}
// 엑셀 파일 다운로드
public function downloadExcel($data, $file_name = 'excel_file.xlsx')
{
// 데이터가 비어있으면 다운로드하지 않음
if (empty($data)) {
echo "출력할 데이터 없음.";
return;
}
// 새 스프레드시트 객체 생성
$spreadsheet = new PhpSpreadsheetObj();
// 첫 번째 시트 선택
$sheet = $spreadsheet->getActiveSheet();
// 데이터를 시트에 작성
$rowIndex = 1; // 엑셀의 첫 번째 행
foreach ($data as $row) {
$columnIndex = 1; // 첫 번째 열
foreach ($row as $cell) {
$sheet->setCellValueByColumnAndRow($columnIndex, $rowIndex, $cell);
$cellCoordinate = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($columnIndex) . $rowIndex;
$sheet->getStyle($cellCoordinate)->applyFromArray([
'alignment' => [
'horizontal' => Alignment::HORIZONTAL_CENTER,
'vertical' => Alignment::VERTICAL_CENTER,
],
'borders' => [
'allBorders' => [
'borderStyle' => Border::BORDER_THIN,
'color' => ['argb' => 'FF000000'],
],
],
]);
$columnIndex++;
}
$rowIndex++;
}
// 열 너비 자동 조절
$columnCount = count($data[0]); // 첫 행 기준 열 개수
for ($col = 1; $col <= $columnCount; $col++) {
$columnLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col);
$sheet->getColumnDimension($columnLetter)->setAutoSize(true);
}
// Excel 파일을 다운로드하도록 설정
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $file_name . '"');
header('Cache-Control: max-age=0');
// 파일 출력
$writer->save('php://output');
exit;
}
}
반응형
3. 사용방법
1) 파일 내보내기
$this->load->library('spreadsheet');
1. 내보내기
$data = [
['이름', '나이', '직업'], // 첫번째 헤더
['홍길동', 30, '개발자'],
];
// 엑셀 다운로드 실행
$this->spreadsheet->downloadExcel($data, 'sample_data.xlsx');
2) 파일 읽기
$sheet = $this->spreadsheet->readExcel('파일');
foreach ($sheet as $key => $row) {
echo $row['A'] // 이름.. 홍길동
echo $row['B'] // 나이.. 30
}
728x90
반응형
'IT > PHP | CI' 카테고리의 다른 글
[PHP] 알면 좋은 배열 함수 array_map, array_filter, array_merge , array_diff, array_column, array_unique (0) | 2025.02.27 |
---|---|
[PHP] $_SERVER['REMOTE_ADDR']의 함정: 실제 사용자 IP를 정확히 파악하는 기술 (0) | 2024.09.10 |
[PHP] 쿼리 반복문 없이 효율적으로 실행시키기 (0) | 2024.08.09 |
[PHP] 객체형 배열 값이 존재하는지 확인하는 법 (0) | 2024.07.23 |
[PHP] 포함된 문자 찾기 str_contains(), str_starts_with(), str_ends_with() 및 strpos() (0) | 2024.06.22 |