当我使用php代码生成excel工作表时,在microsoft excel中打开时会显示一些错误

当我使用php代码生成excel工作表时,在microsoft excel中打开时会显示一些错误,php,excel,mysqli,Php,Excel,Mysqli,当我从数据库生成excel工作表时,它会显示一个错误“excel文件与格式不匹配。是否仍要打开它?”,并指示单击“确定”按钮升级excel文件的格式。当我点击ok时,它工作正常。。。但在手机中,它并不开放 我想生成没有错误的microsoft excel文件 //generating Excel File $setSql = "SELECT * from demo table"; $setRec = mysqli_query($db, $setSql); $header_name="DAT

当我从数据库生成excel工作表时,它会显示一个错误“excel文件与格式不匹配。是否仍要打开它?”,并指示单击“确定”按钮升级excel文件的格式。当我点击ok时,它工作正常。。。但在手机中,它并不开放

我想生成没有错误的microsoft excel文件

//generating Excel File
$setSql = "SELECT * from demo table";
$setRec = mysqli_query($db, $setSql);  

$header_name="DATA LIST IN EXCEL";
$Event= "This is a demo";
date_default_timezone_set("Asia/Kolkata");
$date='Export Date:-'.date("l, jS \of F Y h:i:s A");
$columnHeader = ''; 
$columnHeader = "Name" . "\t" . "Date" . "\t". "Mode No" . "\t". "Address" . "\t". "eduction"."\t"."Organisation" . "\t". "Paid Status" . "\t";    
$setData = '';  

while ($rec = mysqli_fetch_row($setRec)) {  
    $rowData = '';  
    foreach ($rec as $value) {  
        $value = '"' . $value . '"' . "\t";  
        $rowData .= $value;  
    }  
    $setData .= trim($rowData) . "\n";  
}    
header("Content-type: application/octet-stream");  
header("Content-Disposition: attachment; filename= file_name.xls");  
header("Pragma: no-cache");  
header("Expires: 0");  
echo $header_name ."\t\t\t\t\t\t\t\n". $Event ."\t\t\t". $date ."\n". ucwords($columnHeader) . "\n" . $setData . "\n";  

这是我们的密码

通知 下载前请先清洁 这是一个棘手的问题。如果输出缓冲区中有一些内容(可能是不正确的包含文件),则会随文件一起发送。因此,您必须在执行任何下载命令之前清除它

将BOM表标题添加到CSV文件 而且,如果您计划使用Excel打开文件,并且文件为UTF8,则必须添加BOM表标题

public function reportAsset($budgetPeriod_id)
    {
        $timeProcess = round(microtime(true) / 1000);
        if ($budgetPeriod_id) {
            $budget = \App\Models\Invoicing\BudgetPeriod::select(['description'])->find((int) $budgetPeriod_id);
            $client = \App\Models\Structure\Client::select(['description'])->find($this->client_id);
            $filename = date('Ymd').'_'.$budget->description . '_' . $client->description . '.csv';
        $headers = [
            'Content-type' => 'text/csv;charset=UTF-8',
            'Content-Disposition' => 'attachment; filename=' . $filename,
            'Pragma' => 'no-cache',
            'Expires' => '0',
        ];

        $output = fopen($filename, "w");
        // JMA: Add BOM header
        fputs($output, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
        fputcsv($output, [_i('Asset_id'), _i('Asset'), _i('Client Category'), _i('Budget'), _i('Spent'), _i('Available'),_i('Spent') .' %', _i('# Invoices')], ';');
        $query = \App\Models\Invoicing\AssetBudget::query();
        $query->has('asset')
            ->has('clientCategory')
            ->with('asset:PROCESS_ID,Identificador_Processo', 'clientCategory:id,description')

            ->orderBy('asset_id', 'clientCategory_id', 'clientCategory.id')
            ->selectRaw('amount as total, asset_id, budgetPeriod_id, clientCategory_id')
            ->where('budgetPeriod_id', $budgetPeriod_id)
            ->chunk($this::BUDGET_CHUNK, function ($chunk_query) use ($budgetPeriod_id, $output, $timeProcess) {

            foreach ((array) $chunk_query as $report) {

                foreach ($report as $rep) {

                    $row = [];


                    // JMA: The amount has to be the individual amount per asset
                    //      So. we read asset_invoices where the invoice is in the budget period and category
                    // TODO: Replace this piece of code with consumedBudgetByRequest function in Invoicing BudgetController
                    // TODO: Try with calculateBudget but is not the same structure
                    //$invoices = \App\Library\Invoicing\BudgetCalculator::calculateBudget($rep->budgetPeriod_id, $rep->clientCategory_id, (array)$rep->asset_id);

                    $invoices=AssetInvoice::whereHas('invoice' , function ($invoice) use ($rep) {
                        $invoice->where('budgetPeriod_id',$rep->budgetPeriod_id)
                        ->where('clientCategory_id',$rep->clientCategory_id);
                        }
                    )
                        ->selectRaw('count(asset_id) as nInvoices, sum(amount) as spent')
                        ->where('asset_id',$rep->asset_id)
                        ->first();

                    // Log::debug('BudgetController->reportAsset: Invoices found='.$invoices->nInvoices.' spent='.$invoices->spent);

                    $row['asset_id'] = $rep->asset->PROCESS_ID;
                    $row['Identificador_Processo'] = $rep->asset->Identificador_Processo;
                    $row['clientCategory'] = $rep->clientCategory->description;
                    $row["budget"] = floatval($rep->total);
                    $row["spent"] = floatval($invoices->spent);
                    $row["available"] = $row["budget"] - $row["spent"];
                    if(floatval($rep->total)==0 ){
                        $row["percentaje"] = '';
                    }else{
                        $row["percentaje"] = number_format((float)(floatval($invoices->spent)*100)/ floatval($rep->total), 2, '.', ''); 
                    }

                    $row["nInvoices"] = floatval($invoices->nInvoices);
                    // Uncomment this line to monitor time consumption
                    // $row["times"] = $timeProcess - round(microtime(true) / 1000);

                    fputcsv($output, $row, ';');

                }

            }
        });

        fclose($output);

        // CHECK THIS: Clean output buffer before sending files (avoid initial whitespaces)
        if (ob_get_contents()) {
            ob_clean();
        }
        // Send csv file as response
        return response()->download($filename, $filename, $headers)->deleteFileAfterSend(true);

    }

您尝试生成的不是Excel文件,因为这些文件不包含由选项卡分隔的原始数据,可能是添加的代码的副本。待定的对等审查您正在创建扩展名为xls的CSV文件。您可以做两件事:将文件命名为CSV并在excel中打开它而不出错;或者您可以使用PHPEXCEL之类的php库将文件编写为真正的XLS文件。解释在我之前的回答中,但主持人将其删除。请参阅代码中的注释:
//检查此项:在发送文件之前清理输出缓冲区(避免初始空白)。