Excel不保存为数字格式(MySQL到Excel)

时间:2014-03-19 17:55:35

标签: mysql excel matlab matrix

我有一个脚本,允许我将数据库从MySQL转换为Excel .xls格式,这是成功的,

这是代码

<?php

// DB TABLE Exporter
//
// How to use:
//
// Place this file in a safe place, edit the info just below here
// browse to the file, enjoy!

// CHANGE THIS STUFF FOR WHAT YOU NEED TO DO
     $cdate = date("Y-m-d");
     $dbhost  = "localhost";
     $dbuser  = "-";
     $dbpass  = "-";
     $dbname  = "-";
     $dbtable = "-";
     $filename = "C:\xxx";


// END CHANGING STUFF


// first thing that we are going to do is make some functions for writing out
// and excel file. These functions do some hex writing and to be honest I got 
// them from some where else but hey it works so I am not going to question it 
// just reuse


// This one makes the beginning of the xls file
function xlsBOF() {
    echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
    return;
}

// This one makes the end of the xls file
function xlsEOF() {
    echo pack("ss", 0x0A, 0x00);
    return;
}

// this will write text in the cell you specify
function xlsWriteLabel($Row, $Col, $Value ) {
    $L = strlen($Value);
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    echo $Value;
    return;
}



// make the connection an DB query
$dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
mysql_select_db( $dbname );
$q = "SELECT * FROM ".$dbtable." ";
$qr = mysql_query( $q ) or die( mysql_error() );

//start the object
 ob_start();

// start the file
xlsBOF();

// these will be used for keeping things in order.
$col = 0;
$row = 0;

// This tells us that we are on the first row
$first = true;

while( $qrow = mysql_fetch_assoc( $qr ) )
{
    // Ok we are on the first row
    // lets make some headers of sorts
    if( $first )
    {
        // di comment karena ini ngasih label tabelnya, sepertinya nggak butuh
        //foreach( $qrow as $k => $v )
        //{
        //   // take the key and make label
        //   // make it uppper case and replace _ with ' '
        //   xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
        //   $col++;
        //}

        // prepare for the first real data row
        $col = 0;
        $row = 0;//$row++; // nyoba
        $first = false;
    }

    // go through the data
    foreach( $qrow as $k => $v )
    {

        // write it out
        xlsWriteLabel( $row, $col, $v );
        $col++;
    }

    // reset col and goto next row
    $col = 0;
    $row++;

}

xlsEOF();

//write the contents of the object to a file
file_put_contents($filename, ob_get_clean());

?>

此代码生成了一个.xls文件。我使用Matlab通过readxls函数读取我的.xls文件,但是它没有将.xls文件中的值识别为数字数据,因此我在matlab上的脚本无法通过读取我的xls文件来创建矩阵。我不得不在excel中手动转换它,在值附近有一些弹出窗口可以将它转换成数字

1 个答案:

答案 0 :(得分:1)

如果您的目标是从MySQL获取数据并将其放入Matlab,那么从Matlab直接连接MySQL可能更容易,而不是通过xls格式发送数据。

http://www.mathworks.com/help/database/ug/database.fetch.html