php - 将我的 php 表数据导出到 csv 并下载
问题描述
我试图让我的数据库获取数据到 Excel 文件以将其下载到 execl 或 csv 中,但我在导出时遇到问题。不是数据被提取到 csv 。这是我的代码:
<div><a href="javascript:void(0)" id="export-to-csv">Export to csv</a></div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="export-form">
<input type="hidden" value='' id='hidden-type' name='ExportType'/>
</form>
<table id="data-table" class="table table-bordered table-striped">
<thead>
<tr style="background-color: cornflowerblue;">
<th>Invoice No.</th>
<th>Invoice Date</th>
<th>Student Name</th>
<th>Total Amount</th>
</tr>
</thead>
<?php
if($total_rows > 0)
{
foreach($all_result as $row)
{
echo '
<tr>
<td>'.$row["order_no"].'</td>
<td>'.$row["order_date"].'</td>
<td>'.$row["order_receiver_name"].'</td>
<td>'.$row["order_total_after_tax"].'</td>
</tr>
';
}
}
?>
</table>
<?php
}
?>
解决方案
//将此函数添加到脚本标签
function fnExcelReport()
{
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('data-table'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
推荐阅读
- javascript - 为什么 React Hook useEffect 警告缺少依赖项:'props'?
- micronaut - 无法通过发布请求反序列化枚举值
- java - 如何在 URL 中使用动态 ID 处理 Chrome 浏览器中的身份验证弹出窗口
- python - 在 Pandas 中修复一列 RPT 文件
- javascript - 什么是查询:使用 nodeJS 的 url.parse() 中的 [Object: null prototype]
- excel - `excel.application` 的 PowerShell 文档在哪里?
- javascript - 使用带有可变 ID 的数据目标
- swiftui - SwiftUI - 如何从 SwiftUI 访问 UIHostingController
- css - 是否可以将 CSS 添加到具有特定名称的 span 类的特定 ul 中?
- javascript - 如何获取加载 js 文件的下拉列表?