Xuất dữ liệu từ mysql ra excel sử dụng PHP
Trong nội dung của bài này tôi sẽ giới thiệu đến các bạn cách xuất dữ liệu từ mysql ra excel sử dụng PHP . Để làm được việc đó chúng ta bắt đầu như sau:
Trước tiên kết nối đến cơ sở dữ liệu
[codesyntax lang=”php”]
Tiếp đến
[codesyntax lang=”php”]
Tiếp theo chúng ta sẽ đọc dữ liệu từ cơ sở dữ liệu ra và viết lệnh ghi dữ liệu
[codesyntax lang=”php”]
Bạn thấy không xuất dữ liệu từ Mysql ra excel quá đơn giản !
Và code đầy đủ như sau:
[codesyntax lang=”php”]
Chúc bạn lap trinh web thành công !
Xem thêm:
>>> Địa chỉ in catalogue giá rẻ
>>> Chuyên in mác quần áo giá rẻ
Trước tiên kết nối đến cơ sở dữ liệu
[codesyntax lang=”php”]
$host = 'localhost';[/codesyntax]
$user_host = 'root';
$pass = 'root';
$conn=mysql_connect("localhost","root","root") or die("can't connect");
mysql_select_db("vietpro",$conn);
Tiếp đến
[codesyntax lang=”php”]
$filename = "sampledata.xls"; // tên file mặc định[/codesyntax]
// Download file
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
Tiếp theo chúng ta sẽ đọc dữ liệu từ cơ sở dữ liệu ra và viết lệnh ghi dữ liệu
[codesyntax lang=”php”]
// lay du lieu tu trong bang products[/codesyntax]
$sql="SELECT name,price FROM products";
$result=mysql_query($sql);
// ghi du lieu ra file
$flag = false;
while($row = mysql_fetch_assoc($result)) {
if(!$flag) {
// viet ten cot giong ten truong trong bang
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
Bạn thấy không xuất dữ liệu từ Mysql ra excel quá đơn giản !
Và code đầy đủ như sau:
[codesyntax lang=”php”]
<?php[/codesyntax]
$host = 'localhost';
$user_host = 'root';
$pass = 'root';
$conn=mysql_connect("localhost","root","root") or die("can't connect");
mysql_select_db("vietpro_ci",$conn);
$sql="SELECT name,price FROM products";
$result=mysql_query($sql);
$filename = "sampledata.xls"; // File Name
// Download file
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
// Write data to file
$flag = false;
while($row = mysql_fetch_assoc($result)) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
?>
Chúc bạn lap trinh web thành công !
Xem thêm:
>>> Địa chỉ in catalogue giá rẻ
>>> Chuyên in mác quần áo giá rẻ
Comments
Post a Comment