怎么php导出excel是空白
require_once'E:\wamp5.5\wamp\www\config.php';//连接数据库
$link=mysql_connect($config['db']['hostname'],$config['db']['usename'],$config['db']['password']);
mysql_query("set names utf8");
mysql_select_db($config['db']['database']);
$sql="select * from usename " ;
//echo $sql;
$result=mysql_query($sql);
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment; filename=test_data.xls");
echo 'ID'.chr(9);
echo 'name'.chr(9);
echo 'password'.chr(9);
echo chr(13);
while($row=mysql_fetch_assoc($result))
{
//输出到xls
echo $row['id'].chr(9);
echo $row['usename'].chr(9);
echo $row['password'].chr(9);
echo chr(13);
}
?> 展开
你要给出的代码来才能找出问题啊,不够给一个例子给你看看。
下面有几种方法。
基本上导出的文件分为两种:
1:类Excel格式,这个其实不是传统意义上的Excel文件,只是因为Excel的兼容能力强,能够正确打开而已。修改这种文件后再保存,通常会提示你是否要转换成Excel文件。
优点:简单。
缺点:难以生成格式,如果用来导入需要自己分别编写相应的程序。
2:Excel格式,与类Excel相对应,这种方法生成的文件更接近于真正的Excel格式。
如果导出中文时出现乱码,可以尝试将字符串转换成gb2312,例如下面就把$yourStr从utf-8转换成了gb2312:
$yourStr = mb_convert_encoding("gb2312", "UTF-8", $yourStr);
一、PHP导入Excel
1:还是用PHPExcel,官方网站: http://www.codeplex.com/PHPExcel。
2:使用PHP-ExcelReader,下载地址: http://sourceforge.net/projects/phpexcelreader
举例:
<?php
require_once 'Excel/reader.php';
// ExcelFile($filename, $encoding);
$data = new Spreadsheet_Excel_Reader();
// Set output Encoding.
$data->setOutputEncoding('utf8');
$data->read(' jxlrwtest.xls');
error_reporting(E_ALL ^ E_NOTICE);
for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
echo """.$data->sheets[0]['cells'][$i][$j]."",";
}
echo "\n";
}
?>
总结 php导出Excel php导入Excel PhpExcel使用说明 PhpExcel使用手册
方法一:特点,简单,省心,制表符"\t"用户分割同一行中的列,换行符"\t\n"可以开启下一行,还能够自动识别日期格式,货币格式等!
<?php
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=test_data.xls");
//输出内容如下:
echo "姓名"."\t";
echo "年龄"."\t";
echo "学历"."\t";
echo "\n";
echo "张三"."\t";
echo "25"."\t";
echo "本科"."\t";
?>
动态版
<?
$sql = "SELECT * FROM " .$ecs->table('member'). " ";
$classres = $db->Execute($sql);
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment; filename=test_data.xls");
echo 'ID'.chr(9);
echo 'txtPEOClientCode'.chr(9);
echo 'jcompany'.chr(9);
echo 'fcompany'.chr(9);
echo 'ecompany'.chr(9);
echo 'rcompany'.chr(9);
echo 'txtAddress'.chr(9);
echo 'txtCompanyTel'.chr(9);
echo 'txtFax'.chr(9);
echo 'txtPostCode'.chr(9);
echo chr(13);
while ($classrow = $classres->FetchRow())
{
//输出到xls
echo $classrow['id'].chr(9);
echo $classrow['txtPEOClientCode'].chr(9);
echo $classrow['jcompany'].chr(9);
echo $classrow['fcompany'].chr(9);
echo $classrow['ecompany'].chr(9);
echo $classrow['rcompany'].chr(9);
echo $classrow['txtAddress'].chr(9);
echo $classrow['txtCompanyTel'].chr(9);
echo $classrow['txtFax'].chr(9);
echo $classrow['txtPostCode'].chr(9);
echo chr(13);
}
现在用的Php-excel(http://code.google.com/p/php-excel/downloads/list),代码也很简单:
require (dirname (__FILE__) . "./class-excel-xml.inc.php");
$sql = "SELECT * FROM " .$ecs->table('member'). " ";
$classres = $db->Execute($sql);
while($classrow = $classres->FetchRow())
{
$doc[] = array ($classrow['txtPEOClientCode'], $classrow['jcompany'], $classrow['txtBillTo']);
}
$xls = new Excel_XML;
$xls->addArray($doc);
$xls->generateXML("mytest");
我用的utf-8,结果有乱码问题,把class-excel-xml.inc.php utf8_encode($v) 替换成$v就没有乱码问题了。
1:第一推荐无比风骚的PHPExcel,官方网站: http://www.codeplex.com/PHPExcel
导入导出都成,可以导出office2007格式,同时兼容2003。
下载下来的包中有文档和例子,大家可以自行研究。
抄段例子出来:
http://www.codeplex.com/PHPExcel
<?php
ini_set("display_errors",1);//是否显示报错信息
ini_set('include_path', ini_get('include_path').';D:\\PHP\\PHPExcel 1.6.6\\Tests\\classes\\');//设置此页面包含路径
include "classes/PHPExcel.php";
include "classes/PHPExcel/Writer/Excel5.php";
//创建一个excel
$objPHPExcel = new PHPExcel();
$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
$objWriter->save("xxx.xls");
?>
--------------------------------------------------------------------------------------
<?
//设置PHPExcel类库的include path
set_include_path('.'. PATH_SEPARATOR .'D:\workspace\biznaligy_eh\dev_src\includes\PHPExcel' . PATH_SEPARATOR . get_include_path());
require_once 'PHPExcel.php';
require_once 'PHPExcel/Writer/Excel5.php'; // 用于其他低版本xls
require_once 'PHPExcel/Writer/Excel2007.php'; // 用于 excel-2007 格式
// 创建一个处理对象实例
$objExcel = new PHPExcel();
// 创建文件格式写入对象实例, uncomment
$objWriter = new PHPExcel_Writer_Excel5($objExcel); // 用于其他版本格式
//or
//$objWriter = new PHPExcel_Writer_Excel2007($objExcel); // 用于 2007 格式
//$objWriter->setOffice2003Compatibility(true);
//设置文档基本属性
$objProps = $objExcel->getProperties();
$objProps->setCreator("Zeal Li");
$objProps->setLastModifiedBy("Zeal Li");
$objProps->setTitle("Office XLS Test Document");
$objProps->setSubject("Office XLS Test Document, Demo");
$objProps->setDescription("Test document, generated by PHPExcel.");
$objProps->setKeywords("office excel PHPExcel");
$objProps->setCategory("Test");
//设置当前的sheet索引,用于后续的内容操作。
//一般只有在使用多个sheet的时候才需要显示调用。
//缺省情况下,PHPExcel会自动创建第一个sheet被设置SheetIndex=0
$objExcel->setActiveSheetIndex(0);
$objActSheet = $objExcel->getActiveSheet();
//设置当前活动sheet的名称
$objActSheet->setTitle('测试Sheet');
//设置单元格内容
//由PHPExcel根据传入内容自动判断单元格内容类型
$objActSheet->setCellValue('A1', '字符串内容'); // 字符串内容
$objActSheet->setCellValue('A2', 26); // 数值
$objActSheet->setCellValue('A3', true); // 布尔值
$objActSheet->setCellValue('A4', '=SUM(A2:A2)'); // 公式
//显式指定内容类型
$objActSheet->setCellValueExplicit('A5', '847475847857487584', PHPExcel_Cell_DataType::TYPE_STRING);
//合并单元格
$objActSheet->mergeCells('B1:C22');
//分离单元格
$objActSheet->unmergeCells('B1:C22');
//设置单元格样式
//设置宽度
$objActSheet->getColumnDimension('B')->setAutoSize(true);
$objActSheet->getColumnDimension('A')->setWidth(30);
$objStyleA5 = $objActSheet->getStyle('A5');
//设置单元格内容的数字格式。
//如果使用了 PHPExcel_Writer_Excel5 来生成内容的话,
//这里需要注意,在 PHPExcel_Style_NumberFormat 类的 const 变量定义的
//各种自定义格式化方式中,其它类型都可以正常使用,但当setFormatCode
//为 FORMAT_NUMBER 的时候,实际出来的效果被没有把格式设置为"0"。需要
//修改 PHPExcel_Writer_Excel5_Format 类源代码中的 getXf($style) 方法,
//在 if ($this->_BIFF_version == 0x0500) { (第363行附近)前面增加一
//行代码:
//if($ifmt === '0') $ifmt = 1;
//设置格式为PHPExcel_Style_NumberFormat::FORMAT_NUMBER,避免某些大数字
//被使用科学记数方式显示,配合下面的 setAutoSize 方法可以让每一行的内容
//都按原始内容全部显示出来。
$objStyleA5 ->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
//设置字体
$objFontA5 = $objStyleA5->getFont();
$objFontA5->setName('Courier New');
$objFontA5->setSize(10);
$objFontA5->setBold(true);
$objFontA5->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
$objFontA5->getColor()->setARGB('FF999999');
//设置对齐方式
$objAlignA5 = $objStyleA5->getAlignment();
$objAlignA5->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
$objAlignA5->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
//设置边框
$objBorderA5 = $objStyleA5->getBorders();
$objBorderA5->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objBorderA5->getTop()->getColor()->setARGB('FFFF0000'); // color
$objBorderA5->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objBorderA5->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objBorderA5->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
//设置填充颜色
$objFillA5 = $objStyleA5->getFill();
$objFillA5->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$objFillA5->getStartColor()->setARGB('FFEEEEEE');
//从指定的单元格复制样式信息.
$objActSheet->duplicateStyle($objStyleA5, 'B1:C22');
//添加图片
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('ZealImg');
$objDrawing->setDescription('Image inserted by Zeal');
$objDrawing->setPath('./zeali.net.logo.gif');
$objDrawing->setHeight(36);
$objDrawing->setCoordinates('C23');
$objDrawing->setOffsetX(10);
$objDrawing->setRotation(15);
$objDrawing->getShadow()->setVisible(true);
$objDrawing->getShadow()->setDirection(36);
$objDrawing->setWorksheet($objActSheet);
//添加一个新的worksheet
$objExcel->createSheet();
$objExcel->getSheet(1)->setTitle('测试2');
//保护单元格
$objExcel->getSheet(1)->getProtection()->setSheet(true);
$objExcel->getSheet(1)->protectCells('A1:C22', 'PHPExcel');
//输出内容
$outputFileName = "output.xls";
//到文件
////$objWriter->save($outputFileName);
//or
//到浏览器
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Disposition:inline;filename="'.$outputFileName.'"');
header("Content-Transfer-Encoding: binary");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
$objWriter->save('php://output');
?>
首先看看你的excel 文档有没有数据,
检查phpexcel 类文件有没有引入报错什么的
可以使用xdebug 调试输出打印的每一个步骤,以便了解程序运行的正确性
如果还是不明白怎么去调试,如果还是不明白可以尝试第5点
点击我的主页 有问题可以讨论交流,有练习方式哦
set_time_limit(0);
require_once './data/excel/PHPExcel.php';
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("./Public/Book1.xls");
$objWorksheet = $objPHPExcel->getSheet(0);
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$excelData = array();
//注意列数和行数的起始位置
for ($row = 2; $row <= $highestRow;$row++){
for ($col=0;$col<$highestColumnIndex;$col++) {
$excelData[$row][]=(string)$objWorksheet->getCellByColumnAndRow($col,$row)->getValue();
}
}
$map = M('map_info');
//获取该地图的;
foreach($excelData as $key => $val){
//此处需要对自定义的字段序列map_map_custom.cid
$result = curl_get('http://api.map.baidu.com/geocoder/v2/?address=云南鲁甸'.$val[1].'&output=json&ak=2d9a98266c38177f3ef9688f3c228243');
$info = json_decode($result,true);
$data= array(
'uid' => 139,
'mid'=>441,
'tid'=>1472,
'status'=>0,
'title' => $val[0],
'contents' => $val[2],
'create_time' => time(),
'coordinate_lng'=>$info['result']['location']['lng'] ? $info['result']['location']['lng'] : '',
'coordinate_lat'=>$info['result']['location']['lat'] ? $info['result']['location']['lat'] : '',
);
$id = $map -> add($data);
unset($data);
echo $id." --- 成功";
}
//dump($data);
exit;
}
上面是导入数据
public function export_excel(){
$map_info = D("MapInfo");
$mid = intval($_GET["mid"]);
$mapinformation = M("map_info");
$search_type = $_REQUEST['search_type'];
$keywords = t($_REQUEST['keywords']);
$status = $_REQUEST['status'];
if(!empty($status) || $status === '0'){
$where['status'] = $status;
$map['status'] = $status;
}
$where['uid'] = $this->uid;
$where['is_del'] = 0;
if(empty($search_type) && !empty($_REQUEST['keywords'])){
$map['search_type'] = $search_type;
$map['keywords'] = $keywords;
$_search_where['title'] = array('like',"%".$keywords."%");
$_search_where['contents'] = array('like',"%".$keywords."%");
$_search_where['_logic'] = 'or';
$where['_complex'] = $_search_where;
}elseif(!empty($search_type) && !empty($_REQUEST['keywords'])){
$map['search_type'] = $search_type;
$map['keywords'] = $keywords;
$where[$search_type] = array('like',"%".$keywords."%");;
}
$map = D('Map');
if($mid){
$where['mid'] = $mid;
$excel_title = $map->where("mid=$mid") -> getField('title');
$map_info_field = "title,contents,map_info";
}else{
$excel_title = "我的全部地图数据";
$map_info_field = "title,contents,mid";
}
$info_list = $map_info -> getAllMapInfo($mid,$where,$map_info_field);
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=".$excel_title."-".date("Ymd",time()).".xls");
echo iconv('utf-8', 'gb2312', '标题'); echo "\t";
echo iconv('utf-8', 'gb2312', '简介'); echo "\t";
if(!$mid){
echo iconv('utf-8', 'gb2312', '地图名称'); echo "\t";
}else{
$custom_list = D('MapCustom') -> getCustomList($mid);
foreach($custom_list as $k =>$v){
if($v['title']){
echo iconv('utf-8', 'gb2312', $v['title']); echo "\t";
}
}
}
echo "\n";
$order = array("'•'","'\r\n'", "'\n'", "'\r'","'\s+'");//正则匹配回车,换行,空格
$replace = array('','','','','');
foreach($info_list as $key => $val){
echo mb_convert_encoding(preg_replace($order,$replace,strip_tags($val['title']) ) ,'gb2312', 'utf-8'); echo "\t";
echo mb_convert_encoding(preg_replace($order,$replace,strip_tags($val['contents']) ) ,'gb2312', 'utf-8'); echo "\t";
if(!$mid){
$map_title = $map->where("mid=".$val['mid'])->getField('title');
echo iconv('utf-8', 'gb2312', preg_replace($order,$replace,$map_title) ); echo "\t";
echo "\n";
}else{
foreach($custom_list as $ke => $va){
echo iconv('utf-8', 'gb2312', preg_replace($order,$replace, strip_tags( $val['map_info'][$va['cid']] ) ) ); echo "\t";
}
echo "\n";
}
}
}
PHPEXCEL类最好自己下载,我只是提交一个文件而已