(PHPExcel)读取表格中数据
程序员文章站
2022-06-14 08:11:24
...
在实际项目中常常会读取文件或表格中的数据,本篇文章简要介绍了如何使用PHPExcel读取Excel表格中的数据。
首先需要获取PHPExcel对象,即,$this->objPHPExcel = new SfLib_PHPExcel($this->sourceFile);
public function __construct($file = null)
{
parent::__construct();
if (!empty($file))
{
$this->file = $file;
$this->fileObj = $this->load($file);
}
}
public function load($file)
{
try
{
$inputFileType = PHPExcel_IOFactory::identify($file);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
// $objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($file);
$this->file = $file;
$this->fileObj = $objPHPExcel;
return $objPHPExcel;
} catch (PHPExcel_Reader_Exception $e)
{
throw new SfLib_Error(SfLib_Error_Code::PHPEXCEL_ERROR_READ_FAIL, "读取excel文件失败");
}
}
public function readLine()
{
$objPHPExcel = $this->fileObj;
$currentSheet = $objPHPExcel->getSheet(0);
$highestRow = $currentSheet->getHighestRow(); // 取得总行数
$highestColumn = $currentSheet->getHighestColumn(); // 取得总列数
$highestColumn = PHPExcel_Cell::columnIndexFromString($highestColumn);
$table = [];
for ($row = 1; $row <= $highestRow; $row++)
{
$line = [];
for ($column = 0; $column < $highestColumn; $column++)
{
$columnIndex = PHPExcel_Cell::stringFromColumnIndex($column);
$line [] = $currentSheet->getCell($columnIndex . $row)->getValue();
}
if (empty(array_filter($line, function ($item) {
return !empty($item);
})))
{
continue;
}
$table[] = $line;
}
return $table;
}
将excel转换成数组或Json
/*
* 转化Excel数据到json格式
*/
public function transformExcel2Json()
{
$data = $this->objPHPExcel->readLine();
if (! $data) {
echo "read excel data fail.";
exit(-1);
}
$newData = [];
$skipFlag = true;
foreach($data as $row) {
$tmp = [];
if ($skipFlag) {
$skipFlag = false;
continue;
}
$tmp["shop_id"] = intval($row[0]);
$tmp["package_id"] = intval($row[1]);
$tmp["package_name"] = strval($row[2]);
$tmp["net_start_time"] = $this->transformExcelNumber2DateStr(intval($row[3]));
$tmp["end_time"] = $this->transformExcelNumber2DateStr(intval($row[4]));
$tmp["origin_price"] = intval($row[5]);
$tmp["real_price"] = intval($row[6]);
$newData[] = $tmp;
}
var_dump($newData);
$ret = file_put_contents($this->dstFile, json_encode($newData));
if (false === $ret) {
echo "write json file fail";
exit(-1);
}
}
说一下file_put_contents方法,如下: $filename文件内容及格式为
{"name":"\u738b\u5c27","age":"26","sex":"\u5973"}
执行下面的代码, $arr = array( 'name'=>'张三', 'age'=>'26', 'sex'=>'男', ); $str = json_encode($arr); $ret = file_put_contents($filename,$str,FILE_APPEND); if (false === $ret) { Sf_Log::warning("write json file fail"); echo "write json file fail"; }
结果为:
{"name":"\u738b\u5c27","age":"26","sex":"\u5973"}
{"name":"\u5f20\u4e09","age":"26","sex":"\u7537"}
上一篇: phpexcel 用法总结
下一篇: phpexcel-填充颜色问题