2016-05-29 114 views
3

因此,我當前的代碼工作100%,文件生成並在Excel中打開。但是在打開文件時,必須點擊一些錯誤才能打開文件。它們分別是:PHP創建的Excel工作表在創建時會產生錯誤

The file format and extension of 'address-book.xls' 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?

然後:

Excel has detected that 'address-book.xls 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.

後來總算:

The file format and extension of 'address-book.xls' 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?

之後,它不情願地打開。這是創建它的代碼。 格式化電子表格的任何幫助,例如讓單元格足夠大以容納內容會很好。但是在開放時擺脫錯誤是我的首要任務。 ?

<?PHP 
require_once('conn.php'); 

$colnames = array(
    'id' => "ID", 
    'Title' => "Title", 
    'First_Name' => "First name", 
    'Last_Name' => "Last Name", 
    'Address' => "Address", 
    'City' => "City", 
    'State' => "State", 
    'Zipcode' => "Zipcode", 
    'Home_Phone' => "Home Phone", 
    'Cell_Phone' => "Cell Phone", 
    'Email1' => "Email #1", 
    'Email2' => "Email #2" 
); 

function map_colnames($input){ 
    global $colnames; 
    return isset($colnames[$input]) ? $colnames[$input] : $input; 
} 
function cleanData(&$str){ 
    $str = preg_replace("/\t/", "\\t", $str); 
    $str = preg_replace("/\r?\n/", "\\n", $str); 
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; 
} 

$filename = "address-book"; 

header("Content-type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=".$filename.".xls"); 
header("Pragma: no-cache"); 
header("Expires: 0"); 
$flag = false; 
$sql = "SELECT * FROM ".$sDB_table." ORDER BY Last_Name"; 
$query = $sDBConn -> prepare($sql); 
$query -> execute(); 
while(false !== ($row = $query->fetch(PDO::FETCH_ASSOC))) { 
    if(!$flag){ 
     $firstline = array_map(__NAMESPACE__ . '\map_colnames', array_keys($row)); 
     echo implode("\t", $firstline) . "\r\n"; 
     $flag = true; 
    } 
    array_walk($row, __NAMESPACE__ . '\cleanData'); 
    echo implode("\t", array_values($row)) . "\r\n"; 
} 
exit; 

>

PHPExcel錯誤:

$colnames = array("Title","First name","Last Name","Address","City","State","Zipcode","Home Phone","Cell Phone","Email #1","Email #2"); 
$col = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'); 

// Add Headers 
for($i=0;$i<count($colnames);$i++){ 
$objPHPExcel->setActiveSheetIndex(0) 
      ->setCellValue($col[$i]."1", $colnames[$i]); 
} 

$sql = "SELECT * FROM ".$sDB_table." ORDER BY Last_Name"; 
$query = $sDBConn -> prepare($sql); 
$query -> execute(); 

$rownum = 1; 
//Add Content 
while(false !== ($row = $query->fetch(PDO::FETCH_ASSOC))) { 
    $rownum++; 
    for($i=0;$i<count($row);$i++){ 
     $objPHPExcel->setActiveSheetIndex(0) 
        ->setCellValue($col[$i]."".$rownum, $row[$i]);   
    } 
} 

當它擊中while語句出現的錯誤,如果我拿的那部分,它的工作原理。

回答

4

問題是ID作爲文件的前兩個字節。這是SYLK文件的簽名,它是Microsoft Excel的前身Multiplan(符號鏈接交換 - SYLK - 文件格式)使用的舊電子表格格式。

解決這個最簡單的方法是避免ID爲您的標題,並使用Id(IIRC,該SYLK簽名是區分大小寫)或Key或某些其他文本值,而不是


你用xls擴展名保存文件,但實際上並未使用Excel格式,只是一種csv格式;因此MS Excel會抱怨格式與擴展名不匹配....或者將擴展名更改爲.csv以匹配您創建的文件的實際格式;或者創建一個真正的BIFF格式的Excel文件


Any help with formatting the spreadsheet, such as having the cells be big enough for the content would be great.

您使用,CSV(帶標籤分離器)不支持任何形式的格式,其中包括列寬格式。如果你需要的話,那麼你需要切換到一個真正的電子表格格式(巧合的是,SYLK是一個真正的電子表格格式,雖然它相當過時,我不會特別推薦它),例如用於真正的xls文件的BIFF,用於xlsx的OfficeOpenXML文件,用於ods文件的OASIS。


,我使用的OfficeOpenXML XLSX文件頭:

// Redirect output to a client’s web browser (Excel2007) 
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
header('Content-Disposition: attachment;filename="01simple.xlsx"'); 
header('Cache-Control: max-age=0'); 
// If you're serving to IE 9, then the following may be needed 
header('Cache-Control: max-age=1'); 
// If you're serving to IE over SSL, then the following may be needed 
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past 
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified 
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1 
header ('Pragma: public'); // HTTP/1.0 
+0

如果你想給它xls'的'的延伸,那麼Excel將如果它以外的任何其他BIFF格式的抱怨;個人而言,我更喜歡'xlsx'使用OfficeOpenXML格式.... OfficeOpenXML過去9年來一直是MS Excel默認格式 –

+0

好吧我會嘗試實現這一點,任何機會,你可以告訴我如何我看起來更改標題看起來如果我將它改爲xlsx? –

+0

如果你想嘗試創建'xlsb'格式,你會很開心,你不會找到任何可以幫助你的庫 –