php 将excel文件写到word中

时间:2022-05-11 07:19:08

利用php写word的方法,网上主导的方法有三种:

1.利用微软提供com组件.我个人是不推荐的,首先是com组件的文档繁杂,用起来也不是很顺手.

2.利用第三方的wordphp的库,这个库的github网址如下

点击打开链接

功能非常强大的一个库,而且不仅支持word格式,还支持pdf等多种格式.如果你需要的功能很多,可以考虑利用这个库.

3.利用html为中介

  • 生成mht格式(和HTML很相似)写入word
  • 纯HTML格式写入word
我个人利用的方法就是这个.

在这里给出一个php函数,利用的就是html页面为中介

function cword($data,$fileName=''){
if(empty($data)) return '';
$data='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">'.$data.'</html>';
$dir = "./docfile/";
if(!file_exists($dir))
mkdir($dir,777,true);
if(empty($fileName))
{
$fileName=$dir.date('His').'.doc';
}
else
{
$fileName =$dir.$fileName.'.doc';
}
$writefile=fopen($fileName,'wb') or die("创建文件失败");//wb以二进制写入
fwrite($writefile,$data);
fclose($writefile);
return $fileName;
}


既然以及使用html为中介,那么从读取excel的方法,也可以利用html为中介,先把excel转化为html,再把对应的html页面存为word文件.

在这里利用的是github上面的zekus/php-excel-reader项目

点击打开链接

由于源文件过大,我就不放代码了,大家自己去链接下载就可以了

下面各一个具体的例子

在这里调用抵用excel_rader2.php里面的方法,将对应的excel调用为对应的方法将其转化为对应的html格式的字符串,然后利用cword函数,保存为word文件


<?php

function cword($data,$fileName=''){
if(empty($data)) return '';
$data='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">'.$data.'</html>';
$dir = "./docfile/";
if(!file_exists($dir))
mkdir($dir,777,true);
if(empty($fileName))
{
$fileName=$dir.date('His').'.doc';
}
else
{
$fileName =$dir.$fileName.'.doc';
}
$writefile=fopen($fileName,'wb') or die("创建文件失败");//wb以二进制写入
fwrite($writefile,$data);
fclose($writefile);
return $fileName;
}

?>

<?php

error_reporting(E_ALL ^ E_NOTICE);
include_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader("example.xls");


$html = "<html>
<head>
<style>
table.excel {
border-style:ridge;
border-width:1;
border-collapse:collapse;
font-family:sans-serif;
font-size:12px;
}
table.excel thead th, table.excel tbody th {
background:#CCCCCC;
border-style:ridge;
border-width:1;
text-align: center;
vertical-align:bottom;
}
table.excel tbody th {
text-align:center;
width:20px;
}
table.excel tbody td {
vertical-align:bottom;
}
table.excel tbody td {
padding: 0 3px;
border: 1px solid #EEEEEE;
}
</style>
</head>

<body>";

$html .= $data->dump(true,true);
$html .= "</body>
</html>";

cword($html , "test1");

?>

<html>
<head>
<style>
table.excel {
border-style:ridge;
border-width:1;
border-collapse:collapse;
font-family:sans-serif;
font-size:12px;
}
table.excel thead th, table.excel tbody th {
background:#CCCCCC;
border-style:ridge;
border-width:1;
text-align: center;
vertical-align:bottom;
}
table.excel tbody th {
text-align:center;
width:20px;
}
table.excel tbody td {
vertical-align:bottom;
}
table.excel tbody td {
padding: 0 3px;
border: 1px solid #EEEEEE;
}
</style>
</head>

<body>
<?php echo $data->dump(true,true); ?>
</body>
</html>