因此,我當前的代碼工作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語句出現的錯誤,如果我拿的那部分,它的工作原理。
如果你想給它xls'的'的延伸,那麼Excel將如果它以外的任何其他BIFF格式的抱怨;個人而言,我更喜歡'xlsx'使用OfficeOpenXML格式.... OfficeOpenXML過去9年來一直是MS Excel默認格式 –
好吧我會嘗試實現這一點,任何機會,你可以告訴我如何我看起來更改標題看起來如果我將它改爲xlsx? –
如果你想嘗試創建'xlsb'格式,你會很開心,你不會找到任何可以幫助你的庫 –