【发布时间】:2026-02-02 19:40:01
【问题描述】:
我有一段用于制作 Excel 导入 (.xlsx) 的代码。我有一个关于插入迭代数组和更改数组标题的问题。
控制器:
$this->load->library('Excel');
$file = 'upload/keuangan.xlsx';
//read file from path
$objPHPExcel = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel->setReadDataOnly(true);
$objPHPExcel = $objPHPExcel->load($file);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); //dari 0
$data['nomor'] = $this->participant_model->get_dummy(false)->result_array();
$num = $this->participant_model->get_dummy(false)->num_rows();
for($row=2; $row <= $highestRow; ++$row){
for($col=0; $col < $highestColumnIndex; ++$col){
$ExcelData[$col] = $objWorksheet->getCellByColumnAndRow($col,$row)->getValue();
}
echo "<pre>";print_r($ExcelData);echo "</pre>";
$this->session->set_flashdata('message_alert','<div class="alert alert-success">Data berhasil dimasukkan</div>');
$this->participant_model->save($ExcelData);
}
型号:
public function save($data_participant){
$this->db->insert('t_keuangan',$data_participant);
}
这是 keuangan.xlsx,它包含一个字符串头。我从第二行中选择。该列可以展开。
No Ijazah Jumlah Keluar 1 Keluar 2 Keluar 3
1234/SH 100000000 21000000 19000000 18000000
2345/SK 120000000 16000000 19000000 13000000
1245/SA 140000000 20000000 15000000 25000000
$ExcelData 的结果是:
Array
(
[0] => 1234/SH
[1] => 100000000
[2] => 21000000
[3] => 19000000
[4] => 18000000
)
Array
(
[0] => 2345/SK
[1] => 120000000
[2] => 16000000
[3] => 19000000
[4] => 13000000
)
Array
(
[0] => 1245/SA
[1] => 140000000
[2] => 20000000
[3] => 15000000
[4] => 25000000
)
我正在尝试将此$ExcelData 放入我的数据库 MySQL 中。我可以在我的数据库中插入$ExcelData,但标题仍然是数字([0]、[1]、[2]、[3]),因为$row 和$col 使用的$getCellByColumnAndRow 是数字.
表头改成后如何将这些数组插入数据库
Array
(
[no_ijazah] => 1245/SA
[jumlah] => 140000000
[keluar_1] => 20000000
[keluar_3] => 15000000
[keluar_4] => 25000000
)
?
【问题讨论】:
-
我没有看到向数据库添加任何内容的代码
-
我添加了插入功能(已编辑)
-
对不起,如果我在这里错了。我已经回答,评论并投票了答案。由于我的声誉是负数,我不知道它是否被计算在内。以及如何使它们变绿?
标签: php arrays codeigniter phpexcel sql-insert