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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写