chore: 添加支持导入Excel的依赖
This commit is contained in:
@@ -350,6 +350,100 @@ class Project extends Base {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 导入Excel文件
|
||||
* @return json
|
||||
*/
|
||||
public function import_excel()
|
||||
{
|
||||
if (IS_POST) {
|
||||
$file = request()->file('excel_file');
|
||||
if (!$file) {
|
||||
$this->error('请选择要导入的文件');
|
||||
}
|
||||
|
||||
// 验证文件类型
|
||||
$ext = strtolower(pathinfo($file->getInfo('name'), PATHINFO_EXTENSION));
|
||||
if (!in_array($ext, ['xls', 'xlsx'])) {
|
||||
$this->error('只支持Excel格式文件(.xls, .xlsx)');
|
||||
}
|
||||
|
||||
// 移动文件到临时目录
|
||||
$info = $file->move(ROOT_PATH . 'data' . DS . 'runtime', '');
|
||||
if (!$info) {
|
||||
$this->error('文件上传失败: ' . $file->getError());
|
||||
}
|
||||
|
||||
$filename = ROOT_PATH . 'data' . DS . 'runtime' . DS . $info->getSaveName();
|
||||
|
||||
// 解析Excel文件
|
||||
$data = [];
|
||||
try {
|
||||
// 引入PHPExcel库
|
||||
vendor('phpoffice.phpexcel.Classes.PHPExcel');
|
||||
|
||||
// 判断文件类型
|
||||
if ($ext == 'xls') {
|
||||
$objReader = \PHPExcel_IOFactory::createReader('Excel5');
|
||||
} else {
|
||||
$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
|
||||
}
|
||||
|
||||
$objPHPExcel = $objReader->load($filename);
|
||||
$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)[0];
|
||||
|
||||
// 确保行数据完整
|
||||
if (count($rowData) >= 6) {
|
||||
// 验证必要字段不为空
|
||||
if (empty(trim($rowData[0])) || empty(trim($rowData[1]))) {
|
||||
continue; // 跳过必填字段为空的行
|
||||
}
|
||||
|
||||
$data[] = [
|
||||
'name' => trim($rowData[0]),
|
||||
'pwd' => trim($rowData[1]),
|
||||
'enterprise' => trim($rowData[2]),
|
||||
'filing' => trim($rowData[3]),
|
||||
'sid' => trim($rowData[4]),
|
||||
'limitationdate' => trim($rowData[5]),
|
||||
'createtime' => getTime()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 删除临时文件
|
||||
unlink($filename);
|
||||
|
||||
// 批量插入数据
|
||||
if (!empty($data)) {
|
||||
$result = Db::name('project')->insertAll($data);
|
||||
if ($result) {
|
||||
$this->success('成功导入 ' . count($data) . ' 条记录');
|
||||
} else {
|
||||
$this->error('导入失败');
|
||||
}
|
||||
} else {
|
||||
$this->error('文件中没有有效数据');
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
// 删除临时文件
|
||||
if (file_exists($filename)) {
|
||||
unlink($filename);
|
||||
}
|
||||
$this->error('文件解析失败: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
$this->error('非法请求');
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试
|
||||
* @return string
|
||||
|
||||
Reference in New Issue
Block a user