我正在尝试下载一个工作正常的excel文件,但是由于我有一些json列,所以当我尝试包含这些列时,它不起作用。到目前为止,我已经尝试过了。
public function salarySheetExcel($id)
{
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=salary-sheet.csv",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$salariesOfMonth = SalaryArchive::find($id)->salaries;
$columns = array('EmployeeCode', 'EmployeeName', 'Weekends','holidays','leaves','absent','present','inform' ,'late','Basic', 'Allowances', 'Allowance Amount',
'Gross', 'Bonus', 'Overtime Logs', 'Overtime Amount','Net Salary','Deduction Logs','Deduction','PF','Total Salary');
$callback = function() use ($salariesOfMonth, $columns)
{
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
foreach($salariesOfMonth as $salary) {
$salary=array($salary->employee->employee_code,$salary->attendance_log, $salary->employee->name, $salaries ,
$salary->basic, $salary->allowance_amount,$salary->gross,
$salary->bonus, $salary->overtime_amount,$salary->net_salary,
$salary->deduction,$salary->pf,$salary->total_salary);
fputcsv($file, $salary);
}
fclose($file);
};
return Response::stream($callback, 200, $headers);
}
它不起作用,但是当我删除$ salary-> attendance_log时,它的工作正常,因为它是我的json列。请帮我解决一下
JSON数据在字符串中包含引号,这就是它不起作用的原因。
使用下面的代码。
$salary=array($salary->employee->employee_code,addslashes($salary->attendance_log), $salary->employee->name, $salaries ,
$salary->basic, $salary->allowance_amount,$salary->gross,
$salary->bonus, $salary->overtime_amount,$salary->net_salary,
$salary->deduction,$salary->pf,$salary->total_salary);
fputcsv($file, $salary);
我认为您需要在添加到json_decode
之前使用fputcsv
。
$log = json_decode($salary->attendance_log, true);
$weekends = $log['weekends'];
$holidays = $log['holidays'];
$leaves = $log['leaves'];
$absent = $log['absent'];
$present = $log['present'];
$inform = $log['inform'];
$late = $log['late'];
$salary=array($salary->employee->employee_code, $salary->employee->name, $weekends, $holidays, $leaves, $absent, $present, $inform, $late, $salaries ,
$salary->basic, $salary->allowance_amount,$salary->gross,
$salary->bonus, $salary->overtime_amount,$salary->net_salary,
$salary->deduction,$salary->pf,$salary->total_salary);
fputcsv($file, array_merge($salary, $log));