获取一列中的数据

时间:2018-02-18 14:29:20

标签: php html mysql excel

我现在正尝试将数据从我的数据库导出到excel文件。但是,当我打开excel文件时,数据全部在一列中。我想从一列中的MySql数据库中的一行获取所有内容。示例所有用户名应该在一列中,一列中的所有firstnames都是一个

Php代码:

<?php


//include database configuration file
include ('connection.php');

//get records from database
$sql = ("SELECT * FROM employee ORDER BY username DESC");

if($result = mysqli_query($conn, $sql)){
    if(mysqli_num_rows($result) > 0){ 
    $delimiter = ",";
    $filename = "members_" . date('Y-m-d') . ".csv";

    //create a file pointer
    $f = fopen('php://memory', 'w');

    //set column headers
    $field1 = "username"; 
    $field2 = "firstname"; 
    $field3 = "lastname"; 
    $field4 = "phonenumber"; 
    $field5 = "password"; 
    $fields = array($field1 . $field2 . $field3 . $field4 . $field5); 
    fputcsv($f, $fields, $delimiter);

    //output each row of the data, format line as csv and write to file pointer
    while($row = mysqli_fetch_array($result)){ 

        $lineData = array($row['username'], $row['firstname'], $row['lastname'], $row['phonenumber'], $row['password']);
        fputcsv($f, $lineData, $delimiter);
    }

    //move back to beginning of file
    fseek($f, 0);

    //set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');

    //output all remaining data on a file pointer
    fpassthru($f);
}
}
exit;


?>

我的HTML代码:

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <div class="container">
    <div class="panel panel-default">
        <div class="panel-heading">
            Members list
            <a href="exportData.php" class="btn btn-success pull-right">Export Members</a>
        </div>
        <div class="panel-body">
            <table class="table table-bordered">
                <thead>
                    <tr>
                      <th>Name</th>
                      <th>Email</th>
                      <th>Phone</th>
                      <th>Created</th>
                      <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                    //include database configuration file
                    include 'connection.php';

                    //get records from database
                    $sql = ("SELECT * FROM employee ORDER BY username DESC");
                    if($sql->num_rows > 0){ 
                            if(mysqli_num_rows($result) > 0){  ?>                
                    <tr>
                      <td><?php echo $row['name']; ?></td>
                      <td><?php echo $row['email']; ?></td>
                      <td><?php echo $row['phone']; ?></td>
                      <td><?php echo $row['created']; ?></td>
                      <td><?php echo ($row['status'] == '1')?'Active':'Inactive'; ?></td>
                    </tr>
                    <?php } }else{ ?>
                    <tr><td colspan="5">No member(s) found.....</td></tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>

过去2小时我一直在谷歌搜索,无法找到解决方案。你知道一些工具或语言或解决方法吗?

BR

2 个答案:

答案 0 :(得分:1)

在公共HTML表格中显示数据,然后转换&amp;下载excel文件

&#13;
&#13;
var xport = {
  _fallbacktoCSV: true,  
  toXLS: function(tableId, filename) {   
    this._filename = (typeof filename == 'undefined') ? tableId : filename;
    
    //var ieVersion = this._getMsieVersion();
    //Fallback to CSV for IE & Edge
    if ((this._getMsieVersion() || this._isFirefox()) && this._fallbacktoCSV) {
      return this.toCSV(tableId);
    } else if (this._getMsieVersion() || this._isFirefox()) {
      alert("Not supported browser");
    }

    //Other Browser can download xls
    var htmltable = document.getElementById(tableId);
    var html = htmltable.outerHTML;

    this._downloadAnchor("data:application/vnd.ms-excel" + encodeURIComponent(html), 'xls'); 
  },
  toCSV: function(tableId, filename) {
    this._filename = (typeof filename === 'undefined') ? tableId : filename;
    // Generate our CSV string from out HTML Table
    var csv = this._tableToCSV(document.getElementById(tableId));
    // Create a CSV Blob
    var blob = new Blob([csv], { type: "text/csv" });

    // Determine which approach to take for the download
    if (navigator.msSaveOrOpenBlob) {
      // Works for Internet Explorer and Microsoft Edge
      navigator.msSaveOrOpenBlob(blob, this._filename + ".csv");
    } else {      
      this._downloadAnchor(URL.createObjectURL(blob), 'csv');      
    }
  },
  _getMsieVersion: function() {
    var ua = window.navigator.userAgent;

    var msie = ua.indexOf("MSIE ");
    if (msie > 0) {
      // IE 10 or older => return version number
      return parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)), 10);
    }

    var trident = ua.indexOf("Trident/");
    if (trident > 0) {
      // IE 11 => return version number
      var rv = ua.indexOf("rv:");
      return parseInt(ua.substring(rv + 3, ua.indexOf(".", rv)), 10);
    }

    var edge = ua.indexOf("Edge/");
    if (edge > 0) {
      // Edge (IE 12+) => return version number
      return parseInt(ua.substring(edge + 5, ua.indexOf(".", edge)), 10);
    }

    // other browser
    return false;
  },
  _isFirefox: function(){
    if (navigator.userAgent.indexOf("Firefox") > 0) {
      return 1;
    }
    
    return 0;
  },
  _downloadAnchor: function(content, ext) {
      var anchor = document.createElement("a");
      anchor.style = "display:none !important";
      anchor.id = "downloadanchor";
      document.body.appendChild(anchor);

      // If the [download] attribute is supported, try to use it
      
      if ("download" in anchor) {
        anchor.download = this._filename + "." + ext;
      }
      anchor.href = content;
      anchor.click();
      anchor.remove();
  },
  _tableToCSV: function(table) {
    // We'll be co-opting `slice` to create arrays
    var slice = Array.prototype.slice;

    return slice
      .call(table.rows)
      .map(function(row) {
        return slice
          .call(row.cells)
          .map(function(cell) {
            return '"t"'.replace("t", cell.textContent);
          })
          .join(",");
      })
      .join("\r\n");
  }
};
&#13;
<h1>Html table to excel or csv <small style="font-size:17px">---With export for IE and Edge</small></h1>

<p> Test1: <button id="btnExport" onclick="javascript:xport.toXLS('testTable');"> Export to XLS</button> <em>&nbsp;&nbsp;&nbsp;Export the table to XLS with CSV fallback for IE & Edge</em>
  </p>

<p>Test 2: <button id="btnExport" onclick="javascript:xport.toCSV('testTable');"> Export to CSV</button> <em>&nbsp;&nbsp;&nbsp;Export the table to CSV for all browsers</em>
  </p>

<p> Test3: <button id="btnExport" onclick="javascript:xport.toXLS('testTable', 'outputdata');"> Export to XLS</button> <em>&nbsp;&nbsp;&nbsp;Export the table to XLS with custom filename</em>
  </p>
<br />

<table id="testTable" summary="Code page support in different versions of MS Windows." rules="groups" frame="hsides" border="2" class="table table-striped">
  <caption>CODE-PAGE SUPPORT IN MICROSOFT WINDOWS</caption>
  <colgroup align="center"></colgroup>
  <colgroup align="left"></colgroup>
  <colgroup span="2" align="center"></colgroup>
  <colgroup span="3" align="center"></colgroup>
  <thead valign="top">
    <tr>
      <th>Code-Page<br>ID</th>
      <th>Name</th>
      <th>ACP</th>
      <th>OEMCP</th>
      <th>Windows<br>NT 3.1</th>
      <th>Windows<br>NT 3.51</th>
      <th>Windows<br>95</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1200</td>
      <td style="background-color: #00f; color: #fff">Windows 3.11</td>
      <td></td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>*</td>
    </tr>
    <tr>
      <td>1250</td>
      <td style="font-weight: bold">Windows 3.1 Eastern European</td>
      <td>X</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>1251</td>
      <td>Windows 3.1 Cyrillic</td>
      <td>X</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>1252</td>
      <td>Windows 3.1 US (ANSI)</td>
      <td>X</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>1253</td>
      <td>Windows 3.1 Greek</td>
      <td>X</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>1254</td>
      <td>Windows 3.1 Turkish</td>
      <td>X</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>1255</td>
      <td>Hebrew</td>
      <td>X</td>
      <td></td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>1256</td>
      <td>Arabic</td>
      <td>X</td>
      <td></td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>1257</td>
      <td>Baltic</td>
      <td>X</td>
      <td></td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>1361</td>
      <td>Korean (Johab)</td>
      <td>X</td>
      <td></td>
      <td></td>
      <td>**</td>
      <td>X</td>
    </tr>
  </tbody>
  <tbody>
    <tr>
      <td>437</td>
      <td>MS-DOS United States</td>
      <td></td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
      <td>X</td>
    </tr>
    <tr>
      <td>708</td>
      <td>Arabic (ASMO 708)</td>
      <td></td>
      <td>X</td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>709</td>
      <td>Arabic (ASMO 449+, BCON V4)</td>
      <td></td>
      <td>X</td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>710</td>
      <td>Arabic (Transparent Arabic)</td>
      <td></td>
      <td>X</td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
    <tr>
      <td>720</td>
      <td>Arabic (Transparent ASMO)</td>
      <td></td>
      <td>X</td>
      <td></td>
      <td></td>
      <td>X</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在Excel中打开文件时,需要将其转换为列。

在“数据”(菜单选项或选项卡)下,选择“数据到列”。选择适当的数据格式。很可能,这是用逗号分隔的。

或者,使用制表符分隔符创建文件,该分隔符是Excel中的默认字段分隔符。