使用PHPExcel制作自动生成的excel文件 [英] Using PHPExcel to make automatic generated excel files

查看:78
本文介绍了使用PHPExcel制作自动生成的excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的 excel 文件填充一些我从数据库中获取的数据,例如某人的姓名和年龄.

I want to have my excel file filled with some data which I get from my database, for example the name and age of someone.

假设我的数据库中有 10 个人.我希望我的 Excel 文件中有这 10 个人.

Say there are 10 people in my database. I want those 10 people in my Excel file.

所以基本上,你会得到:

So basically, you would get:

姓名年龄

人 1 20 年

Person2 25 岁

Person2 25 years

等等.我知道如何设置 NAME 和 AGE 的内容,但是我将如何循环数据并将其写入 excel 文件中?我在 PHPExcel 的文档中找不到任何关于它的信息.

And so on. I know how to set the NAME and AGE stuff, but how would I go about looping the data and writing it inside the excel file? I couldn't find anything about it in PHPExcel's documentation.

这是我的 MySQL:

This is my MySQL:

$query = "SELECT * FROM bestelling"; 

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
    $name = $row['name'];
    $age = $row['age'];
}

推荐答案

我假设您已经创建了 excel 对象.我将其称为 $objPHPExcel 以符合他们的示例.在这种情况下,您可以循环结果集并以这种方式填充电子表格:

I'm assuming you already have the excel object created. I'll call it $objPHPExcel to conform to their examples. In that case you can loop your result set and populate the spreadsheet this way:

$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$rowCount = 1;
while($row = mysql_fetch_array($result)){
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['name']);
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['age']);
    $rowCount++;
}
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save('some_excel_file.xlsx');

我已更新示例以提供完整的解决方案.

I have updated the example to provide a complete solution.

这篇关于使用PHPExcel制作自动生成的excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆