Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1532109
  • 博文数量: 194
  • 博客积分: 6450
  • 博客等级: 准将
  • 技术积分: 2085
  • 用 户 组: 普通用户
  • 注册时间: 2005-06-06 13:39
文章分类

全部博文(194)

文章存档

2013年(38)

2012年(11)

2011年(1)

2010年(1)

2009年(4)

2008年(13)

2007年(18)

2006年(63)

2005年(45)

我的朋友

分类:

2005-11-25 19:14:16

Spreadsheet_Excel_Writer 一个不需要COM组件来创建.xls文件的方式,详情参考其中有所需的相关类。

The most common use for Spreadsheet_Excel_Writer will be spitting out large (or not so large) amounts of information in the form of a spreadsheet, which is easy to manipulate with a fairly ubiquitous spreadsheet program such as Excel (or OpenOffice).

So let's cut to the chase and see how this is done:


require_once 'Spreadsheet/Excel/Writer.php';

// Creating a workbook
$workbook = new Spreadsheet_Excel_Writer();

// sending HTTP headers
$workbook->send('test.xls');

// Creating a worksheet
$worksheet =& $workbook->addWorksheet('My first worksheet');

// The actual data

$worksheet->write(0, 0, 'Name');
$worksheet->write(0, 1, 'Address');
$worksheet->write(0, 2, 'Age');
for ($i=1; $i<5; $i++) {
$worksheet->write($i, 0, "name$i");
for ($j=1; $j<5; $j++) {
$worksheet->write($i, 1, "address$j");
}
for ($k=1; $k<5; $k++) {
$worksheet->write($i, 2, "age$j");
}
}

// Let's send the file
$workbook->close();
?>

The first thing you should notice, is that we created a workbook before any worksheets. All worksheets are contained within a workbook, and a workbook may contain several worksheets.

Another important thing, which you should have in mind when programming with Spreadsheet_Excel_Writer, is that ampersand sign (&) that appears when we created our worksheet. That ampersand means we are referencing a Worksheet object instead of copying it. If you don't know what that means, don't worry, all you have to remember is to always use ampersands when calling for creating a worksheet, or for creating a format.

Saving to a regular file

You may have noticed also the following line:

// sending HTTP headers
$workbook->send('test.xls');
What that means is that we are sending our spreadsheet to a browser. But what if we just want to save the spreadsheet in our machine? Well, you just have to omit that line and give a valid file path to the workbook constructor.

For example, if we wanted to save the same spreadsheet we created in our first example to a file named 'test.xls', we would do it like so:


require_once 'Spreadsheet/Excel/Writer.php';

// We give the path to our file here
$workbook = new Spreadsheet_Excel_Writer('test.xls');

$worksheet =& $workbook->addWorksheet('My first worksheet');

$worksheet->write(0, 0, 'Name');
$worksheet->write(0, 1, 'Age');
$worksheet->write(1, 0, 'John Smith');
$worksheet->write(1, 1, 30);
$worksheet->write(2, 0, 'Johann Schmidt');
$worksheet->write(2, 1, 31);
$worksheet->write(3, 0, 'Juan Herrera');
$worksheet->write(3, 1, 32);

// We still need to explicitly close the workbook
$workbook->close();
?>
阅读(1218) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~