簡體   English   中英

我應該如何使用PHP Excel將MYSQL數據導出到Excel中

[英]How should I go about exporting MYSQL data into Excel using PHP Excel

這可能是一個非常不尋常的問題,但我確實被困在這里。 我正在從MYSQL數據庫中讀取數據,並使用Echo通過PHP通過此數據創建表。 現在,我想進行下一步,並將此數據(表中的數據)導出到Excel文檔。 我真的很喜歡PHPExcel的工作方式,以及它的簡單程度,但我很難弄清楚獲取數據的最有效方法,並將其放入excel文檔中。 當然,我不想一直寫到“ Z11000”中的“ A1”,“ A1數據”-明白我的意思嗎? 我相信我應該遍歷一切。 現在,這里的問題變得棘手了。 有什么方法(請記住,這需要通過PHP來完成)以逐個單元(循環)讀取表單元並將值分配給數組,然后像A1,arr [0]等循環遍歷該數組?

我認為我必須使用JavaScript逐個單元地讀取表,但是那又如何將數據分配給數組,以便隨后將其用作PHP腳本的一部分-因為PHPExcel是用PHP編寫的。

這個問題對您中的每個人都有意義嗎,還是我在這里錯過了很多信息? 讓我知道,我可以編輯這個問題,以便對大家都有意義。

理想的解決方案是創建一個與平台無關的 “ Excel”文件,該文件可以通過任何電子表格程序或文本編輯器(不僅限於Excel)打開。 我的意思是一個基本的CSV文件。

幸運的是,不需要外部庫:PHP具有一些內置功能,用於讀取/寫入CSV文件。 因此,將數據從數據庫中取出並放入Excel可讀的csv文件中的步驟如下:

  1. 查詢數據庫並遍歷結果: mysql_result docs
  2. 在遍歷數據庫結果的循環內,使用fputcsv docs編寫csv文件。

現在,您可能想知道如何將創建的csv文件保存到自己的計算機上,而不是保存在剛創建該文件的服務器上。 幸運的是,對此也有一個簡單的解決方案。

假設您希望csv成為您正在生成的頁面的實際內容。 我的意思是,您希望瀏覽器將PHP文件視為本身就是csv文件

將CSV文件存儲在內存中而不是磁盤上

不用在fputcsv操作中使用真實的文件句柄來編寫csv, fputcsv在內存中打開文件句柄以執行相同的操作。 這具有比寫入磁盤更快的優點。 要在內存中打開文件句柄以在fputcsv調用中使用,請執行以下操作:

$tmp_handle = fopen('php://temp', 'r+');

這將打開一個內存文件句柄,而不是在文件系統上。 請注意,一旦文件大小達到文件大小中的默認值2Mb,PHP就會透明地將其切換為文件系統上的臨時文件。 您可以使用以下方法來避免這種情況,並強制文件句柄保留在內存中:

$tmp_handle = fopen('php://memory', 'r+');

然后,您將在調用fputcsv使用此句柄:

fputcsv($tmp_handle, $fields);

您可以在該主題PHP手冊中找到有關php://memoryphp://temp更多信息。

讓瀏覽器認為它是CSV文件

生成數據后,要使瀏覽器說服頁面的最后一件事實際上是一個csv文件,是將正確的HTTP內容類型標頭與數據一起發送:

// generate my csv data here

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');

// reset the file handle's pointer to the beginning of the stream
rewind($tmp_handle);

// output the contents of the file handle to the browser
echo stream_get_contents($tmp_handle);
<?php

//EDIT YOUR MySQL Connection Info:
$DB_Server = "localhost";        //your MySQL Server
$DB_Username = "root";                 //your MySQL User Name
$DB_Password = "";                //your MySQL Password
$DB_DBName = "school";                //your MySQL Database Name
$DB_TBLName = "s_question";                //your MySQL Table Name

if(isset($_POST['exp_stdque'])) {
    $exstdid = $_POST['expstd'];

//$DB_TBLName,  $DB_DBName, may also be commented out & passed to the browser
//as parameters in a query string, so that this code may be easily reused for
//any MySQL table or any MySQL database on your server

//DEFINE SQL QUERY:
//edit this to suit your needs
$sql = "Select * from $DB_TBLName WHERE std_id = $exstdid";

//Optional: print out title to top of Excel or Word file with Timestamp
//for when file was generated:
//set $Use_Titel = 1 to generate title, 0 not to use title
$Use_Title = 1;
//define date for title: EDIT this to create the time-format you need
$now_date = DATE('m-d-Y H:i');
//define title for .doc or .xls file: EDIT this if you want
$title = "Dump For Table $DB_TBLName from Database $DB_DBName on $now_date";
/*

Leave the connection info below as it is:
just edit the above.

(Editing of code past this point recommended only for advanced users.)
*/
//create MySQL connection
$Connect = @MYSQL_CONNECT($DB_Server, $DB_Username, $DB_Password)
     or DIE("Couldn't connect to MySQL:<br>" . MYSQL_ERROR() . "<br>" . MYSQL_ERRNO());
//select database
$Db = @MYSQL_SELECT_DB($DB_DBName, $Connect)
     or DIE("Couldn't select database:<br>" . MYSQL_ERROR(). "<br>" . MYSQL_ERRNO());
//execute query
$result = @MYSQL_QUERY($sql,$Connect)
     or DIE("Couldn't execute query:<br>" . MYSQL_ERROR(). "<br>" . MYSQL_ERRNO());

//if this parameter is included ($w=1), file returned will be in word format ('.doc')
//if parameter is not included, file returned will be in excel format ('.xls')
IF (ISSET($w) && ($w==1))
{
     $file_type = "msword";
     $file_ending = "doc";
}ELSE {
     $file_type = "vnd.ms-excel";
     $file_ending = "xls";
}
//header info for browser: determines file type ('.doc' or '.xls')
HEADER("Content-Type: application/$file_type");
HEADER("Content-Disposition: attachment; filename=database_dump.$file_ending");
HEADER("Pragma: no-cache");
HEADER("Expires: 0");

/*    Start of Formatting for Word or Excel    */

IF (ISSET($w) && ($w==1)) //check for $w again
{
     /*    FORMATTING FOR WORD DOCUMENTS ('.doc')   */
     //create title with timestamp:
     IF ($Use_Title == 1)
     {
         ECHO("$title\n\n");
     }
     //define separator (defines columns in excel & tabs in word)
     $sep = "\n"; //new line character

     WHILE($row = MYSQL_FETCH_ROW($result))
     {
         //set_time_limit(60); // HaRa
         $schema_insert = "";
         FOR($j=0; $j<mysql_num_fields($result);$j++)
         {
         //define field names
         $field_name = MYSQL_FIELD_NAME($result,$j);
         //will show name of fields
         $schema_insert .= "$field_name:\t";
             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));
         //end of each mysql row
         //creates line to separate data from each MySQL table row
         PRINT "\n----------------------------------------------------\n";
     }
}ELSE{
     /*    FORMATTING FOR EXCEL DOCUMENTS ('.xls')   */
     //create title with timestamp:
     IF ($Use_Title == 1)
     {
         ECHO("$title\n");
     }
     //define separator (defines columns in excel & tabs in word)
     $sep = "\t"; //tabbed character

     //start of printing column names as names of MySQL fields
     FOR ($i = 0; $i < MYSQL_NUM_FIELDS($result); $i++)
     {
         ECHO MYSQL_FIELD_NAME($result,$i) . "\t";
     }
     PRINT("\n");
     //end of printing column names

     //start while loop to get data
     WHILE($row = MYSQL_FETCH_ROW($result))
     {
         //set_time_limit(60); // HaRa
         $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);
         //following fix suggested by Josue (thanks, Josue!)
         //this corrects output in excel when table fields contain \n or \r
         //these two characters are now replaced with a space
         $schema_insert = PREG_REPLACE("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
         $schema_insert .= "\t";
         PRINT(TRIM($schema_insert));
         PRINT "\n";
     }
}
}

?>

我有個建議。 例如,如果有人按下導出按鈕,則向php頁面發出POST請求,並執行與從MySQL檢索數據相同的查詢。 一個你得到數據集。 您可以簡單地循環它們並寫入excel。 在下面的代碼中, $dataset是MySQL結果集。

$objPHPExcel = new PHPExcel();


$index = 1;
foreach($dataset as $subscriber)
{
    $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A' . $index, $subscriber['Email']);
    $index ++;
}

如果讓用戶修改屏幕中輸出表中的數據。 假設您在表格內有文本框,還需要將它們保存到excel文件中。 然后,將這些元素命名為數組。 例如: txtName[]因此,一旦獲得POST,就可以以編程方式進行處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM