成功利用php将服务器上的txt文本转换为excel文件,并很好地解决中文不能显示问题。
一个很小的项目,自动收集学生上传的缴学费银行卡信息,简单得要命,干脆就用在服务器上保持为文本的方式实现,然后在财务人员使用时希望用excel将数据保持到个人电脑商,我收集学生自己录入的银行卡信息后,在服务器上 保持了一个bank.txt文件,里面有中文,有长达18位的数字字段,要通过网页将文本转换为excel(直接让财务人员调用文本有点太简单,都丢人,没有那样做),虽然简单,但却遇到好几个问题,数字太长成为科学计数法的问题,结果超过13位的数据都变成0000了,首字符为0的数据丢0的问题(如学号0911****),还有就是中文编码问题,无法在传给excel时正常显示。但最终都一一解决了,现将代码贴下(已经包含php-excel的classic源码了,以备后用:
前提是你的php环境必须安装 '--enable-libxml' 组件,否则不好用。
//将bank文件夹下的bank.txt文件转换为bank.xls存到用户端。
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$file = file("$DOCUMENT_ROOT/bank/bank.txt");
$number_of_file = count($file);
if ($number_of_file == 0) {
echo '
没有录入银行卡信息!
';
exit;
}
for ($i = 0; $i < $number_of_file; $i++) {
$row = explode(",", $file[$i]);
$number_of_row = count($row);
for ($k = 0; $k < $number_of_row; $k++) {
//取得单元数据前,进行字符的转换,将Windows的GB2312字符转换为linux常用的UTF-8,因为在进行数据录入过程中,输入的字符时GB2312编码。
$doc[$i][$k] = iconv("GB2312","UTF-8//IGNORE",$row[$k]);
}
}
$xls = new Excel_XML('UTF-8', false, 'My bank added Sheet');
$xls->addArray( $doc );
$xls->generateXML('bankadded');
//php excel class source including.
/**
*Project:
*/
class Excel_XML
{
private $header = "\n";
private $footer = "";
private $lines = array();
private $sEncoding;
private $bConvertTypes;
private $sWorksheetTitle;
public function __construct($sEncoding = 'UTF-8', $bConvertTypes = false, $sWorksheetTitle = 'Table1')
{
$this->bConvertTypes = $bConvertTypes;
$this->setEncoding($sEncoding);
$this->setWorksheetTitle($sWorksheetTitle);
}
public function setEncoding($sEncoding)
{
$this->sEncoding = $sEncoding;
}
public function setWorksheetTitle ($title)
{
$title = preg_replace ("/[\\\|:|\/|\?|\*|\[|\]]/", "", $title);
$title = substr ($title, 0, 31);
$this->sWorksheetTitle = $title;
}
private function addRow ($array)
{
$cells = "";
foreach ($array as $k => $v):
$type = 'String';
if ($this->bConvertTypes === true && is_numeric($v)):
$type = 'Number';
endif;
$v = htmlentities($v, ENT_COMPAT, $this->sEncoding);
$cells .= "" . $v . " | \n";
endforeach;
$this->lines[] = "\n" . $cells . "
\n";
}
public function addArray ($array)
{
foreach ($array as $k => $v)
$this->addRow ($v);
}
public function generateXML ($filename = 'excel-export')
{
$filename = preg_replace('/[^aA-zZ0-9\_\-]/', '', $filename);
header("Content-Type: application/vnd.ms-excel; charset=" . $this->sEncoding);
header("Content-Disposition: inline; filename=\"" . $filename . ".xls\"");
echo stripslashes (sprintf($this->header, $this->sEncoding));
echo "\n
sWorksheetTitle . "\">\n\n";
foreach ($this->lines as $line)
echo $line;
echo "
\n\n";
echo $this->footer;
}
}
?>
附上我自己的源程序和txt文件。
|
文件: |
txe2xls.rar |
大小: |
1KB |
下载: |
下载 | |
阅读(3395) | 评论(0) | 转发(0) |