我想使用Codeigniter上的库PHPExcel将文件Excel导入Mysql,我的代码成功地将数据插入数据库,但是如果我将类型数据格式更改为整数,字段日期插入数字31248,则日期格式为0000-00-00。 / p>
这是我的控制器功能
public function upload_excel()
{
$fileName = $this->input->post('file', TRUE);
$config['upload_path'] = './assets/excel/';
$config['file_name'] = $fileName;
$config['allowed_types'] = '*';
$config['encrypt_name']= TRUE;
$config['max_size'] = 0;
$this->load->library('Upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('file')) {
$error = $this->upload->display_errors();
$this->session->set_flashdata('pesan',$error);
redirect('sio');
} else {
$media = $this->upload->data();
$inputFileName = './assets/excel/'.$media['file_name'];
try {
$inputFileType = IOFactory::identify($inputFileName);
$objReader = IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($row = 2; $row <= $highestRow; $row++){
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$data = array(
"kd_pekerja"=> trim(preg_replace("/[^a-zA-Z0-9]/", "", $rowData[0][1])), // opsional hapus spasi depan
"no_ktp"=> $rowData[0][2],
"nm_karyawan"=> $rowData[0][3],
"tgl_lahir"=> $rowData[0][4],
"no_sio"=> $rowData[0][5],
"tgl_buat"=> $rowData[0][6],
"ms_berlaku"=> $rowData[0][7],
"ket"=> $rowData[0][8]);
$this->db->insert("tbl_sio",$data);
}
unlink($inputFileName); // hapus file temp
$count = $highestRow;
$this->session->set_flashdata('pesan','Upload berhasil, Total: <b>'.$count.'</b> data.');
redirect('sio');
}
}
答案 0 :(得分:0)
您可以使用PHPExcel_Shared_Date
类
$worksheet=$objPHPExcel->getActiveSheet();
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (PHPExcel_Shared_Date::isDateTime($cell)) {
$date=date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($cell->getValue()));
}
}
}