douye9175 2016-08-01 17:59
浏览 35
已采纳

CSV下载不适用于所有页面

I have a website that I created for reports. There are basically 3 reports. I have a button on each page that calls another PHP page that will download the results of the query that fills the page into a CSV file. This works fine on one page, but on the other two it gives me an error when trying to open. It says:

The file format and extension of 'FileName' don't match. the file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?

I click yes, then get this:

Excel has detected that 'FileName' is a SYLK file, but cannot load it. Either the file has errors or it is not a SYLK file format. Click OK to try to open the file in a different format.

I click OK and it opens fine.

Where as on the other page it just opens.

Here's most of the ExportToExcel.php

switch ($_POST['ExportToExcel'])
{
    case "QDef":
        $tsql = "select Id,QSrc,QName,QDef,isActive,RunReport,FilePath from pmdb.v_QDefs order by Id";

        $hsql = "select Headings from TableHeadings where TableName = 'v_QDefs' and Headings != 'Edit' order by ID";

        break;
    case "TableUpdates":
        $tsql = "select ID, TableName, UpdateDate from pmdb.TableUpdates order by UpdateDate";
        $hsql = "select Headings from TableHeadings where TableName = 'TableUpdates' and Headings != 'Edit' order by ID";
        break;
}

$filename = $_POST['ExportToExcel'];

header("Content-Type: application/x-csv");
header("Content-Disposition: attachment; filename=$filename.csv");
//define separators (defines columns in excel)
$sep = ",";
$br = "
"; //line break

$getHeadings = $conn->query($hsql);
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);

$headings = array();
$NumHeadings = count($rHeadings);

for ($i = 0;$i < $NumHeadings; $i++)
{
    $headings[] = $rHeadings[$i]["Headings"];
}
//start of printing column names as names of SQL fields
foreach($headings as $Heading => $value)
{
    echo "$value" . $sep;
}
//end of printing column names
echo $br; //separate the headers and the data

foreach($conn->query($tsql) as $row)
{
    for ($i = 0;$i < $NumHeadings;$i++)
    {
        $CommentPos = strpos($rHeadings[$i]["Headings"],"comment");
        $NewLines = array("
","
","
","");
        $UseValue = str_replace($NewLines, " ",$row[$i]);
        $UseValue = str_replace('"', "'",$row[$i]);
        $pos = strpos($UseValue,",");
        if ($CommentPos === FALSE || $pos === FALSE || isset($UseValue))
        {
            echo '"' . $UseValue . '"' . $sep;
        }
        else
        {
            echo $UseValue . $sep . "Not quoted";
        }
    }
    echo $br;
}

I have a include at the top that has the connection string for connecting to my MSSQL DB, which does work, or there'd be nothing displayed on the page to begin with.

I just con't figure out why the page doesn't work the same way for all reports when they are all calling the page the same way.

EDIT again

I tried several ideas from below and now I have this:

$filename = $_POST['ExportToExcel'] . '.csv';

$Opened = fopen($filename,'w');

header("Content-Type: text/csv; charset=utf-8'");
header("Content-Disposition: attachment; filename=$filename");

fputcsv($Opened,$headings);

foreach($conn->query($tsql) as $row)
{
    fputcsv($Opened,$row);
}
fclose($Opened);

Which still gives me a blank spreadsheet. So obviously I'm still doing something wrong?

  • 写回答

1条回答 默认 最新

  • dqkmn26444 2016-08-02 14:41
    关注

    Nevermind, I updated the Headings for all the tables that I am trying to export so that the first column is no longer ID, but is instead Id. Since it's no longer all caps it is working fine without the fputcsv since that isn't doing anything for me anyhow.

    $filename = $_POST['ExportToExcel'] . '.csv';
    
    header("Content-Type: text/csv; charset=utf-8'");
    header("Content-Disposition: attachment; filename=$filename");
    
    //define separators (defines columns in excel)
    $sep = ",";
    $br = "
    "; //line break
    
    $getHeadings = $conn->query($hsql);
    $rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
    
    $headings = array();
    $NumHeadings = count($rHeadings);
    
    for ($i = 0;$i < $NumHeadings; $i++)
    {
        $headings[] = $rHeadings[$i]["Headings"];
    }
    
    //start of printing column names as names of SQL fields
    foreach($headings as $Heading => $value)
    {
        echo "$value" . $sep;
    
    }
    
    foreach($conn->query($tsql) as $row)
    {
        for ($i = 0;$i < $NumHeadings;$i++)
        {
            $CommentPos = strpos($rHeadings[$i]["Headings"],"comment");
            $NewLines = array("
    ","
    ","
    ","");
            $UseValue = str_replace($NewLines, " ",$row[$i]);
            $UseValue = str_replace('"', "'",$row[$i]);
            $pos = strpos($UseValue,",");
            if ($CommentPos === FALSE || $pos === FALSE || isset($UseValue))
            {
                echo '"' . $UseValue . '"' . $sep;
            }
            else
            {
                echo $UseValue . $sep . "Not quoted";
            }
        }
    echo $br;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错