2017-06-21 145 views
0

我创建了Html表格,其中有来自mysql表格的数据,现在我想将数据导出为CSV和PDF文件,怎么样?
我想要,当我点击按钮(CSV和PDF分开)时,它会自动下载CSV和PDF格式正确的文件。
我尝试了一些我在网上找到的脚本,但它不工作,有些格式化问题,并保存下载。
在提前谢谢。
如何将Html表格导出为CSV和PDF格式并使用Php

<table id="example2" class="table table-bordered table-hover"> 
       <thead> 
       <tr> 
     <th>District</th> 
     <th>Union Council</th> 
     <th>Village</th> 
     <th>Recreational</th> 
     <th>Awareness Raising</th> 
     <th>Training</th> 
     <th>Social Mobilization</th> 
     <th>Total Activities</th> 

       </tr> 
       </thead> 
        <tbody> 
     <tr> 
     <td style="color:red;"><b><?php echo getTotalDistrictUnique();?></b></td> 
     <td style="color:red;"><b><?php echo getTotalUnionCouncilUnique();?></b></td> 
     <td style="color:red;"><b><?php echo getTotalVillages(); ?></b></td> 
     <td style="color:red;"><b><?php echo getTotalRecreational();?></b></td> 
     <td style="color:red;"><b><?php echo getTotalAwareness();?></b></td> 
     <td style="color:red;"><b><?php echo getTotalTraining();?></b></td> 
     <td style="color:red;"><b><?php echo getTotalSocial();?></b></td> 
     <td style="color:red;"><b><?php echo getTotalRecreational() + getTotalAwareness() + getTotalTraining() + getTotalSocial(); ?></td> 

     </tr> 

     <?php 
include("connection.php"); 
$query ="select * from general"; 
$run =mysqli_query($con,$query); 
while ($row=mysqli_fetch_array($run)) { 
    $id=$row['id']; 
    $createdate=$row[1]; 
    $createday=$row[2]; 
    $partnername=$row[3]; 
    $district=$row[4]; 
    $unioncouncil=$row[5]; 
    $village=$row[6]; 
    $vannumber=$row[7]; 
    $facilitator=$row[8]; 
    $beneficiarytype=$row[9]; 
    $rmultimedia=$row[10]; 
    $rgame=$row[11]; 
    $rsprort=$row[12]; 
    $rart=$row[13]; 
    $rgroupreading=$row[14]; 
    $rother=$row[15]; 
    $alandminer=$row[16]; 
    $apersonalsafety=$row[17]; 
    $abirthregister=$row[18]; 
    $aother=$row[19]; 
    $tstickstone=$row[20]; 
    $tohthers=$row[21]; 
    $sbirthregister=$row[22]; 
    $sother=$row[23]; 
    $formnumber=$row[24]; 
    $submitdatatime=$row[25]; 
?> 

     <tr> 
     <td><?php echo $district?></td> 
     <td><?php echo $unioncouncil?></td> 
     <td><?php echo $village?></td> 
     <td> 
     <?php 
     if($rmultimedia=='true') 
     { 
     $rmultimedia_value = 1; 
     } 
     else{ 
      $rmultimedia_value = 0; 
     } 

     if($rgame=='true') 
     { 
     $rgame_value = 1; 
     } 
     else{ 
      $rgame_value = 0; 
     } 

     if($rsprort=='true') 
     { 
     $rsprort_value = 1; 
     } 
     else{ 
      $rsprort_value = 0; 
     } 

     if($rart=='true') 
     { 
     $rart_value = 1; 
     } 
     else{ 
      $rart_value = 0; 
     } 

     if($rgroupreading=='true') 
     { 
     $rgroupreading_value = 1; 
     } 
     else{ 
      $rgroupreading_value = 0; 
     } 

     if($rother=='true') 
     { 
     $rother_value = 1; 
     } 
     else{ 
      $rother_value = 0; 
     } 

     $recreational_sum = $rmultimedia_value + $rgame_value + $rsprort_value + $rart_value + $rgroupreading_value + $rother_value; 

     echo $recreational_sum;?></td> 

     <td> 
      <?php 
     if($alandminer=='true') 
     { 
     $alandminer_value = 1; 
     } 
     else{ 
      $alandminer_value = 0; 
     } 

     if($apersonalsafety=='true') 
     { 
     $apersonalsafety_value = 1; 
     } 
     else{ 
      $apersonalsafety_value = 0; 
     } 

     if($abirthregister=='true') 
     { 
     $abirthregister_value = 1; 
     } 
     else{ 
      $abirthregister_value = 0; 
     } 

     if($aother=='true') 
     { 
     $aother_value = 1; 
     } 
     else{ 
      $aother_value = 0; 
     } 

     $awareness_raising_sum = $alandminer_value + $apersonalsafety_value + $abirthregister_value + $aother_value; 

     echo $awareness_raising_sum;?> 
     </td> 

     <td> 
       <?php 
     if($tstickstone=='true') 
     { 
     $tstickstone_value = 1; 
     } 
     else{ 
      $tstickstone_value = 0; 
     } 

     if($tohthers=='true') 
     { 
     $tohthers_value = 1; 
     } 
     else{ 
      $tohthers_value = 0; 
     } 

     $training_sum = $tstickstone_value + $tohthers_value; 

     echo $training_sum;?> 
     </td> 

     <td> 
     <?php 
     if($sbirthregister=='true') 
     { 
     $sbirthregister_value = 1; 
     } 
     else{ 
      $sbirthregister_value = 0; 
     } 

     if($sother=='true') 
     { 
     $sother_value = 1; 
     } 
     else{ 
      $sother_value = 0; 
     } 

     $social_mobilization_sum = $sbirthregister_value + $sother_value; 

     echo $social_mobilization_sum;?> 
     </td> 

     <td style="color:red;"><?php echo $recreational_sum + $awareness_raising_sum + $training_sum + $social_mobilization_sum;?></td> 

     </tr> 
<?php } ?> 
    </tbody> 
       </table> 
+0

你应该使用foreach和mysqli_fetch_assoc来获得更多的readbale代码... CSV没有格式化,你可以使用一些phpexcel项目,如https://github.com/PHPOffice/PHPExcel。创建PDF是一个选项 - 请参阅https://tcpdf.org/examples/ - 有很多示例... – Yedidia

+0

您必须尝试此操作,因为在CSv中,我们无法执行格式更多 https:// stackoverflow。 com/questions/4249432/export-to-csv-via-php –

+0

For PDF试试这个 https://stackoverflow.com/questions/10496122/pdf-export-in-php –

回答

1

下载CSV从最终

$(function() { 
 
    $(".export-csv").on('click', function (event) { 
 
     // CSV 
 
     var filename = $(".export-csv").data("filename") 
 
     var args = [$('#fixed_table'), filename + ".csv", 0]; 
 
     exportTableToCSV.apply(this, args); 
 
    }); 
 
    $(".export-txt").on('click', function (event) { 
 
     // txt 
 
     var filename = $(".export-txt").data("filename") 
 
     var args = [$('#fixed_table'), filename + ".txt", 0]; 
 
     exportTableToCSV.apply(this, args); 
 
    }); 
 

 
    
 
    function exportTableToCSV($table, filename, type) { 
 
     var startQuote = type == 0 ? '"' : ''; 
 
     var $rows = $table.find('tr').not(".no-csv"), 
 
      // Temporary delimiter characters unlikely to be typed by keyboard 
 
      // This is to avoid accidentally splitting the actual contents 
 
      tmpColDelim = String.fromCharCode(11), // vertical tab character 
 
      tmpRowDelim = String.fromCharCode(0), // null character 
 
      // actual delimiter characters for CSV/Txt format 
 
      colDelim = type == 0 ? '","' : '\t', 
 
      rowDelim = type == 0 ? '"\r\n"' : '\r\n', 
 
      // Grab text from table into CSV/txt formatted string 
 
      csv = startQuote + $rows.map(function (i, row) { 
 
       var $row = $(row), 
 
        $cols = $row.find('td,th'); 
 
       return $cols.map(function (j, col) { 
 
        var $col = $(col), 
 
         text = $col.text().trim().indexOf("is in cohort") > 0 ? $(this).attr('title') : $col.text().trim(); 
 
        return text.replace(/"/g, '""'); // escape double quotes 
 

 
       }).get().join(tmpColDelim); 
 

 
      }).get().join(tmpRowDelim) 
 
       .split(tmpRowDelim).join(rowDelim) 
 
       .split(tmpColDelim).join(colDelim) + startQuote; 
 
     // Deliberate 'false', see comment below 
 
     if (false && window.navigator.msSaveBlob) { 
 
      var blob = new Blob([decodeURIComponent(csv)], { 
 
       type: 'text/csv;charset=utf8' 
 
      }); 
 

 
       window.navigator.msSaveBlob(blob, filename); 
 

 
     } else if (window.Blob && window.URL) { 
 
      // HTML5 Blob   
 
      var blob = new Blob([csv], { type: 'text/csv;charset=utf8' }); 
 
      var csvUrl = URL.createObjectURL(blob); 
 

 
      $(this) 
 
       .attr({ 
 
        'download': filename, 
 
        'href': csvUrl 
 
       }); 
 
     } else { 
 
      // Data URI 
 
      var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv); 
 

 
      $(this) 
 
       .attr({ 
 
        'download': filename, 
 
        'href': csvData, 
 
        'target': '_blank' 
 
       }); 
 
     } 
 
    } 
 

 
});
<html> 
 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <title>Export CSV</title> 
 
<script 
 
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
 
</script> 
 
    <style type="text/css"> 
 
     #page-wrapper { 
 
      margin: 0 0 0 0; 
 
     } 
 
    </style> 
 
</head> 
 
<body> 
 
    <div id="wrapper"> 
 
     <!-- Page Content --> 
 
     <div id="page-wrapper"> 
 
      <div class="container-fluid"> 
 
       <div class="row"> 
 
        <div class="col-lg-12"> 
 
         
 

 
<style> 
 

 

 
</style> 
 
<h2> 
 
    Export to CSV 
 

 
    <!-- Single button --> 
 
    <span class="btn-group pull-right"> 
 
     <ul class="dropdown-menu"> 
 
      <li><a href=javascript:; class="export-csv" data-filename="CSVFILE">CSV</a></li> 
 
      <li><a href=javascript:; class="export-txt" data-filename="TXTFILE">Flat file</a></li> 
 
     </ul> 
 
    </span> 
 

 
</h2> 
 
<hr /> 
 

 
<div class="row"> 
 
    <div class="col-md-2 col-sm-4 col-xs-12"> 
 

 
    </div> 
 
</div> 
 
<div class="row"> 
 
    <div class="col-md-12"> 
 
     <div class="table-responsive"> 
 
      <table id="fixed_table" class="table table-condensed row-border order-column" cellspacing="0"> 
 
       <thead> 
 
        <tr> 
 
         <th>First Header</th> 
 
         <th >Second Header</th> 
 

 
         
 

 
        </tr> 
 
       </thead> 
 
       <tbody> 
 
         <tr> 
 
          <td class="text-center"> First Row column 1</td> 
 
           <td>First Row column 2</td> 
 
          
 
         </tr> 
 
\t \t \t \t \t \t </tbody> 
 
      </table> 
 
     </div> 
 
    </div> 
 
</div> 
 

 

 

 

 

 

 
</body> 
 
</html>

+0

谢谢,它工作,但PDF? –

+0

我不确定在PHP中我认为你需要的任何PDF库如fPDF –

+0

如果有帮助,请标记回答 –

0

CSV没有格式化,您可以像使用github.com/PHPOffice/PHPExcel一些phpexcel项目。创建PDF是一个选项 - 最为人熟知的是TCPDF,请参阅tcpdf.org/examples - 有很多示例。

0

对于创建CSV文件,你需要数组,可以如下操作:

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'), 
    array('123', '456', '789'), 
    array('"aaa"', '"bbb"') 
); 

$fp = fopen('file.csv', 'w'); 

foreach ($list as $fields) { 
    fputcsv($fp, $fields); 
} 

fclose($fp); 

对于导出HTML表格转换成PDF,您可以使用mpdf

表举例:https://github.com/mpdf/mpdf-examples/blob/development/example05_tables.php

要直接下载文件你也可以做如下:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") { 
    header('Content-Type: application/csv'); 
    header('Content-Disposition: attachment; filename="'.$filename.'";'); 

    // open the "output" stream 
    // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq 
    $f = fopen('php://output', 'w'); 

    foreach ($array as $line) { 
     fputcsv($f, $line, $delimiter); 
    } 
} 

用法:从HTML

array_to_csv_download(array(
    array(1,2,3,4), 
    array(1,2,3,4)), 
    "export.csv" 
); 
+0

我想导出从mysql数据库获取数据的表,所以如何在csv文件上写入表数据 –

+0

选择查询中csv所需的列。 1)打开文件指针$ fp使用fopen,2)循环通过结果while()在该循环中使用fputcsv根据您的字段数组和3)关闭指针 – mukund

+0

当我点击按钮它打开新页面,我粘贴这段代码,但它没有下载文件? –

0

使用此代码获取表值

$row = mysqli_fetch_assoc($sql) //$sql variable used to fetch custom table query 

这里创建CSV文件,里面的值写入csv

$file = fopen("file.csv","w"); //csv file created here with write mode 

foreach ($row as $line){ 
    fputcsv($file,explode(',',$line)); 
} 

fclose($file);     //csv file closed here