Код: Выделить всё
Код: Выделить всё
public function actionDownload()
{
var_dump($_REQUEST);
die(0);
}
Обновленный код
Форма
Код: Выделить всё
Код: Выделить всё
public function actionDownload()
{
$postData = Yii::$app->request->post();
$msnArray = $postData['TaskConfig']['msn'];
// Remove any empty values from the array
$msnArrayFilter = array_filter($msnArray);
if (empty($msnArrayFilter)) {
Yii::$app->session->setFlash('error', 'No meters selected.');
return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);
}
$dataProvider = new ActiveDataProvider([
'query' => TaskConfig::find()->select(['msn', 'ak', 'ek', 'utility'])->where(['msn' => $msnArrayFilter]),
'pagination' => false,
]);
$models = $dataProvider->getModels();
// Create Excel file
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Set headers
$sheet->setCellValue('A1', 'Msn');
$sheet->setCellValue('B1', 'Ak');
$sheet->setCellValue('C1', 'Ek');
$sheet->setCellValue('D1', 'Utility');
// Fill data
$row = 2;
foreach ($msnArray as $msn)
{
// Assuming TaskConfig::find() returns models with the same attributes as the Excel columns
$model = TaskConfig::find()->where(['msn' => $msn])->one();
if ($model !== null) {
$sheet->setCellValue('A' . $row, $model->msn);
$sheet->setCellValue('B' . $row, $model->ak);
$sheet->setCellValue('C' . $row, $model->ek);
$sheet->setCellValue('D' . $row, $model->utility);
$row++;
}
}
// Save the Excel file content to a temporary file
$microseconds = microtime(true); // Get current timestamp with microseconds
$microseconds = str_replace('.', '', $microseconds); // Remove the dot from microseconds
$filename = 'task_config_' . date('YmdHis') . '_' . $microseconds . '.xlsx';
try {
// Save Excel file to temporary location
$tempFilePath = sys_get_temp_dir() . '/' . $filename;
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($tempFilePath);
// Send the file content to the user for download
Yii::$app->response->sendFile($tempFilePath, $filename)->send();
return;
} catch (\Throwable $e) {
// Handle any exceptions
Yii::error('Error generating Excel file: ' . $e->getMessage());
Yii::$app->session->setFlash('error', 'An error occurred while generating the Excel file.');
return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);
}
}
Подробнее здесь: https://stackoverflow.com/questions/782 ... t2-in-yii2