茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1729034 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
PIMG_00167.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

PHP特區 : [分享]如何使用php將mysql的查詢結果導出為excel

發表者 討論內容
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[分享]如何使用php將mysql的查詢結果導出為excel
冷日因為需要一個從網頁上(PHP)產出Excel格式檔案的功能,所以去拜了Google大神,得到的訊息如下:

//發送一個excel的頭子生成xsl ------這段代碼應該在最前面
header( "Content-type:application/vnd.ms-excel "); 
header( "Content-Disposition:filename=test.xls "); 


我的思路是:查詢後,有一個結果顯示頁,該頁有一個鏈接:
導出為xsl //傳遞一個export給本頁,export=yes,即為要導出

該頁的頭部有這一段:
<?php 
//發送一個excel的頭子生成xsl       ------這段代碼應該在最前面 
if($export== "yes ") 
{ 
        header( "Content-type:application/vnd.ms-excel "); 
        header( "Content-Disposition:filename=test.xls "); 
} 
?> 


經測試,沒那麼單純!
所以又參閱了以下幾篇。
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]php如何倒出Excel檔案

         Everybody knows phpMyAdmin can export file to Excel format but phpMyAdmin just export .csv file,not real Excel file format. If you are interest in PHP programming and need to export to the real Excel format please check it out !

Example PHP export to XLS file format.

1. Create Function for XLS

function xlsBOF () {
    echo
pack ( "ssssss" , 0x809 , 0x8 , 0x0 ,
0x10 , 0x0 , 0x0 );  
    return;
}

function
xlsEOF () {
    echo
pack ( "ss" , 0x0A , 0x00 );
    return;
}

function
xlsWriteNumber ( $Row , $Col , $Value ) {
    echo
pack ( "sssss" , 0x203 , 14 , $Row , $Col , 0x0 );
    echo
pack ( "d" , $Value );
    return;
}

function
xlsWriteLabel ( $Row , $Col , $Value
) {
    
$L = strlen ( $Value );
    echo
pack ( "ssssss" , 0x204 , 8 + $L , $Row , $Col , 0x0 , $L );
    echo
$Value ;
return;
}



2. Send Header to Browser in download format.

    // Query Database
    
$result = mysql_db_query ( $dbname , "select id,prename,name,sname,grade from appdata where course='$courseid' and sec='$section'" )

    
// Send Header
    
header ( "Pragma: public" );

    
header ( "Expires: 0" );
    
header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
    
header ( "Content-Type: application/force-download" );
    
header ( "Content-Type: application/octet-stream" );
    
header ( "Content-Type: application/download"
);;
    
header ( "Content-Disposition: attachment;filename=$courseid-$sec.xls " ); // �ล้วนี่�็ชื่อไฟล์
    
header ( "Content-Transfer-Encoding: binary " );

    
// XLS Data Cell


                
xlsBOF ();
                
xlsWriteLabel ( 1 , 0 , "Student Register $semester/$year" );
                
xlsWriteLabel ( 2 , 0 , "COURSENO : " );

                
xlsWriteLabel ( 2 , 1 , "$courseid" );
                
xlsWriteLabel ( 3 , 0 , "TITLE : " );
                
xlsWriteLabel ( 3 ,
1 , "$title" );
                
xlsWriteLabel ( 4 , 0 , "SETION : " );
                
xlsWriteLabel ( 4 , 1 , "$sec" );
                

xlsWriteLabel ( 6 , 0 , "NO" );
                
xlsWriteLabel ( 6 , 1 , "ID" );
                
xlsWriteLabel ( 6 , 2 , "Gender"
);
                
xlsWriteLabel ( 6 , 3 , "Name" );
                
xlsWriteLabel ( 6 , 4 , "Lastname" );
                
$xlsRow = 7 ;

                while(list(
$id , $prename , $name , $sname , $grade )= mysql_fetch_row ( $result )) {
                    ++
$i ;
                          
xlsWriteNumber
( $xlsRow , 0 , "$i" );
                          
xlsWriteNumber ( $xlsRow , 1 , "$id" );
                          
xlsWriteLabel ( $xlsRow , 2
, "$prename" );
                          
xlsWriteLabel ( $xlsRow , 3 , "$name" );
                          
xlsWriteLabel ( $xlsRow , 4 , "$sname" );

                    
$xlsRow ++;
                    }
                    
xlsEOF ();
                 exit();



原文出處:AppServNetwork - Easy way to create XLS file from PHP
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]php-excel(export)

php-excel(export)

<?
class Excel_XML
{

    /**
     * Header of excel document (prepended to the rows)
     */
    var $header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?\><Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";

    /**
     * Footer of excel document (appended to the rows)
     */
    var $footer = "</Workbook>";
    /**
     * Style of the content
     */
    var $style = "<Styles>
  <Style ss:ID=\"s34\">
   <Alignment ss:Horizontal=\"Center\" ss:Vertical=\"Bottom\"/>

   <Borders>
    <Border ss:Position=\"Bottom\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\"/>
    <Border ss:Position=\"Left\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\"/>
    <Border ss:Position=\"Right\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\"/>
    <Border ss:Position=\"Top\" ss:LineStyle=\"Continuous\" ss:Weight=\"1\"/>
   </Borders>
   <Font x:Family=\"Swiss\" ss:Size=\"11\" ss:Bold=\"1\"/>
   <Interior ss:Color=\"#CCFFCC\" ss:Pattern=\"Solid\"/>
  </Style>
  <Style ss:ID=\"s21\">
   <Alignment ss:Vertical=\"Center\" ss:WrapText=\"1\"/>
  </Style>
 </Styles>";
    /**
     * Document lines (rows in an array)
     */
    var $lines = array ();

    /**
     * Worksheet title
     *
     * Contains the title of a single worksheet
     */
    var $worksheet_title = "Service Request Hitlist";
    /**
     * Add a single row to the $document string
     */
    function addRow ($array)
    {

        // initialize all cells for this row
        $cells = "";

        // foreach key -> write value into cells
        foreach ($array as $k => $v):
           
            //tranform the \n to the right format in excel

            $v = str_replace("\n","&#10;",$v);
            $cells .= "<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">" . utf8_encode($v) . "</Data></Cell>\n";

        endforeach;

        // transform $cells content into one row
        $this->lines[] = "<Row>\n" . $cells . "</Row>\n";

    }
    /**
     * Add an array to the document
     *
     * This should be the only method needed to generate an excel
     * document.
     */
    function addArray ($array)
    {

        // run through the array and add them into rows
        // The first element of $array is the header array
        $headArray = $array[0];
        for($i=1;$i<count($array);$i++){   
            $dataArray[] = $array[$i];
        }
        $headCell = "";
        foreach ($headArray as $k => $v):
            $headCell .= "<Cell ss:StyleID=\"s34\"><Data ss:Type=\"String\">" . utf8_encode($v) . "</Data></Cell>\n";
        endforeach;
        $this->lines[] = "<Row>\n" . $headCell . "</Row>\n";

               
        foreach ($dataArray as $k => $v):
            $this->addRow ($v);
        endforeach;

    }
    /**
     * Set the worksheet title
     */
    function setWorksheetTitle ($title)
    {

        // strip out special chars first
        $title = preg_replace ("/[\\\|:|\/|\?|\*|\[|\]]/", "", $title);

        // now cut it to the allowed length
        $title = substr ($title, 0, 31);

        // set title

        $this->worksheet_title = $title;

    }
   /**
     * Generate the excel file
     */
    function generateXML ($filename)
    {

        // deliver header (as recommended in php manual)
        header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
        header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");

        // print out document to the browser
        // need to use stripslashes for the damn ">"

        echo stripslashes ($this->header);
        echo stripslashes ($this->style);
        echo "\n<Worksheet ss:Name=\"" . $this->worksheet_title . "\">\n<Table>\n";
        echo "<Column ss:Index=\"1\" ss:AutoFitWidth=\"0\" ss:Width=\"60\"/>\n";
        echo implode ("\n", $this->lines);
        echo "</Table>\n</Worksheet>\n";
        echo $this->footer;
    }
}
// create a dummy array
$doc = array (
         array ("name", "sex", "age"),
         array ("Marlene", "male", "22"),
         array ("linda\n ma", "female", "24")
    );


// generate excel file
$xls = new Excel_XML;
$xls->addArray ( $doc );
$xls->generateXML ("mytest");
?>

原文出處:php-excel(export) - 若水汪洋的空間 - PHPChina 開源社區門戶
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]MYSQL到EXCEL的轉換程序
MYSQL到EXCEL的轉換程序
<?php
// define database parameter

$dbHost = "localhost";
$dbUsername = "webuser";
$dbPassword = "123456";
$dbDbName = "pa_bbs";
$dbTablename = "pw_actions";

// connect database

$Connect = @mysql_connect($dbHost, $dbUsername, $dbPassword) or die("Couldn't connect.");
$Db = @mysql_select_db($dbDbName, $Connect) or die("Couldn't select database.");

// set header infomation

$file_type = "vnd.ms-excel";
$file_ending = "xls";
header("Content-Type: application/$file_type");
header("Content-Disposition: attachment; filename=$dbTablename.$file_ending");
header("Pragma: no-cache");
header("Expires: 0");

// export data to excel
date_default_timezone_set('Asia/Shanghai');

$now_date = date('Y-m-d H:i:s');
$title = "數據庫名:$dbDbName, 數據表:$dbTablename, 備份日期:$now_date";
echo("$title\n");
$sql = 'set names gbk;';
@mysql_query($sql,$Connect);
$sql = 'select * from '.$dbTablename.';';
$ALT_Db = @mysql_select_db($dbDbName, $Connect) or die("Couldn't select database");
$result = @mysql_query($sql,$Connect) or die(mysql_error());

$sep = "\t";
for ($i = 0; $i < mysql_num_fields($result); $i++) {
    echo mysql_field_name($result,$i) . "\t";
}
print("\n");
$i = 0;
while($row = mysql_fetch_row($result)) {
    $schema_insert = "";
    for($j=0; $j<mysql_num_fields($result);$j++) {
        if(!isset($row[$j]))
            $schema_insert .= "NULL".$sep;
        elseif ($row[$j] != "")

            $schema_insert .= "$row[$j]".$sep;
        else
            $schema_insert .= "".$sep;
    }
    $schema_insert = str_replace($sep."$", "", $schema_insert);
    $schema_insert .= "\t";
    print(trim($schema_insert));
    print "\n";
    $i++;
}
return (true);
?> 

原文出處: MYSQL到EXCEL的轉換程序 - WEB開發 - 月亮他哥
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[分享]冷日的 php query mssql 2 excel 範例
然後,冷日經過爬文整理之後,終於自己轉出 Excel 成功了,這裡把冷日的Code借大家參考一下!
先做點說明:
1.Web 端是 LAMP 系統,只是這次沒有採用 MySql
2.所以冷日是拿 php 連結 MsSql

先來做資料連線的設定:
<?php
// define database parameter
$dbHost = "192.168.OOO.XXX";  //資料庫IP
$dbUsername = "OOXX";         //資料庫連線帳號
$dbPassword = "OOXXOOXXOOXX"; //資料庫連線密碼
$dbDbName = "OOXX";           //資料庫名稱
$dbTablename = "OOOXXX";      //資料表名稱

// connection to the database
$Connect = mssql_connect($dbHost, $dbUsername, $dbPassword)
    or die("Couldn't connect to SQL Server on $dbHost");

// select a database to work with
$selected = mssql_select_db($dbDbName, $Connect)
    or die("Couldn't open database $dbDbName");
?>


然後是輸出 Excel 最重要得 Header 部份:
<?php
// set header infomation
$file_type = "vnd.ms-excel";
$file_ending = "xls";
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/$file_type");
header("Content-Disposition: attachment; filename=$dbTablename.$file_ending");
header("Content-Transfer-Encoding: binary ");
header("Pragma: no-cache");
header("Expires: 0");
?>


然後去把資料庫撈出來:
<?php
// export data to excel
$sql = 'SELECT * FROM ' . $dbTablename . ' WHERE (type IS NOT NULL) ORDER BY sn ;';
//$ALT_Db = @mysql_select_db($dbDbName, $Connect) or die("Couldn't select database");
//$result = @mysql_query($sql,$Connect) or die(mysql_error());
$result = @mssql_query($sql,$Connect) or die(mysql_error());
?>


設定第一行的表頭:
<?php
$sep = "\t";
$title2Write = array('產品編號' , '產品序號' , '產品類別' , '產品名稱' , '產品單位' , '產品單價' , '最低訂量' );
for ( $i = 0 ; $i < 7 ; $i++ ) {
	echo iconv( "UTF-8" , "big5" , $title2Write[$i] ) . "\t";
}
print("\n");
?>


把資料開始塞到 Excel 的所有欄位:
<?php
$i = 0;
while($row = mssql_fetch_row($result)) {
    $schema_insert = "";
    for( $j = 0 ; $j < mssql_num_fields($result) ; $j++ ) {
        if(!isset($row[$j]))
            $schema_insert .= "NULL".$sep;
        elseif ($row[$j] != "")
            $schema_insert .= "$row[$j]".$sep;
        else
            $schema_insert .= "".$sep;
    }
    $schema_insert = str_replace($sep."$", "", $schema_insert);
    $schema_insert .= "\t";
    print(trim($schema_insert));
    print "\n";
    $i++;
}?>


嘗試把自己關掉:
<script language="javascript">
	window.opener=null;
	window.open("","_self");
	window.close();
</script>


最後那個嘗試把自己關掉的功能經測試後無效,不過呢,冷日本來要的功能,就是在某個網頁上做一個 link ,當使用者點擊此 link 時,會即時的去資料庫查詢出資料並製作成 Excel 給使用者下載,所以把自己關掉不會動也沒關係了啦!
筆痕
Re: [分享]冷日的 php query mssql 2 excel 範例
由訪客「php」所發表的文章。
---

前輩你好, 請問如果要讓User點連結後把搜尋資料結果轉乘EXCEL
要如何做呢? 謝
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[回覆]讓User點連結後把搜尋資料結果轉成EXCEL
引言:

由訪客「php」所發表的文章。
---

前輩你好, 請問如果要讓User點連結後把搜尋資料結果轉乘EXCEL
要如何做呢? 謝


冷日:
說真的,冷日對於這個問題,有點納悶!
依照冷日上一篇([分享]冷日的 php query mssql 2 excel 範例)的說法,應該可以解決這個疑惑不是嗎?
問題的癥結再哪呢?沒有思考過?沒有Code的能力?沒有Code的經驗?或是根本沒有把上一篇看懂呢?冷日真的有點疑惑,不知道要用哪個角度切入來回答這問題!

好吧,冷日自己當作自己是初心者,來看待這個『讓User點連結後把搜尋資料結果轉成EXCEL』需求如何用「[分享]冷日的 php query mssql 2 excel 範例」來解決會是這樣的思路:
1.要給使用者點擊的連結要先做出來!
2.該連結的href會是我們寫出來的php程式,比方說:searchResult2Excel.php
3.searchResult2Excel.php的內容應該和[分享]冷日的 php query mssql 2 excel 範例裡面的Code幾乎一模一樣!
大致上會長這樣:
<?php //先來做資料連線的設定:
// define database parameter
$dbHost = "192.168.OOO.XXX";  //資料庫IP
$dbUsername = "OOXX";         //資料庫連線帳號
$dbPassword = "OOXXOOXXOOXX"; //資料庫連線密碼
$dbDbName = "OOXX";           //資料庫名稱
$dbTablename = "OOOXXX";      //資料表名稱

// connection to the database
$Connect = mssql_connect($dbHost, $dbUsername, $dbPassword)
    or die("Couldn't connect to SQL Server on $dbHost");

// select a database to work with
$selected = mssql_select_db($dbDbName, $Connect)
    or die("Couldn't open database $dbDbName");
?>
<?php  //然後是輸出 Excel 最重要得 Header 部份:
// set header infomation
$file_type = "vnd.ms-excel";
$file_ending = "xls";
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/$file_type");
header("Content-Disposition: attachment; filename=$dbTablename.$file_ending");
header("Content-Transfer-Encoding: binary ");
header("Pragma: no-cache");
header("Expires: 0");
?>
<?php  //然後去把資料庫撈出來:
// export data to excel
$sql = 'SELECT * FROM ' . $dbTablename . ' WHERE `OOColnum` LIKE '%SearchKeyWord%' ;';  //這裡就是搜尋字串和搜尋欄位的sql語法,也就是說,你原本的搜尋資料怎麼作,這裡就是帶入一樣的sql語法就好啦!
//$ALT_Db = @mysql_select_db($dbDbName, $Connect) or die("Couldn't select database");
//$result = @mysql_query($sql,$Connect) or die(mysql_error());
$result = @mssql_query($sql,$Connect) or die(mysql_error());
?>
<?php  //設定第一行的表頭:
$sep = "\t";
$title2Write = array('產品編號' , '產品序號' , '產品類別' , '產品名稱' , '產品單位' , '產品單價' , '最低訂量' );  //因為你搜尋的資料表定義冷日完全無法預想,請自己依據你搜尋的資料表欄位填入Excel表頭
for ( $i = 0 ; $i < 7 ; $i++ ) {
	echo iconv( "UTF-8" , "big5" , $title2Write[$i] ) . "\t";
}
print("\n");
?>
<?php  //把資料開始塞到Excel 的所有欄位:
$i = 0;
while($row = mssql_fetch_row($result)) {
    $schema_insert = "";
    for( $j = 0 ; $j < mssql_num_fields($result) ; $j++ ) {
        if(!isset($row[$j]))
            $schema_insert .= "NULL".$sep;
        elseif ($row[$j] != "")
            $schema_insert .= "$row[$j]".$sep;
        else
            $schema_insert .= "".$sep;
    }
    $schema_insert = str_replace($sep."$", "", $schema_insert);
    $schema_insert .= "\t";
    print(trim($schema_insert));
    print "\n";
    $i++;
}?>

4.這不就完工了?換言之,根本就是[分享]冷日的 php query mssql 2 excel 範例抄一抄就有答案啦!

冷日到現在還是不解這個問題的癥結在哪裡!
前一個主題 | 下一個主題 | 頁首 | | |



Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|