纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示:
写入到city.xls文件中:
{
"1" : "上海",
"2" : "北京",
"3" : "成都"
}
代码:
<?php
/**
* 把txt中的json数据导入到excel中
* Created by PhpStorm.
* User: Administrator
* Date: 2016/12/9
* Time: 19:02
*/
require_once 'Common/PHPExcel/Classes/PHPExcel.php';
//读取文件并且转json为数组
$json = file_get_contents('15/city.txt');
$array = json_decode($json, true);
$PHPExcel = new PHPExcel();
$PHPExcel_write = new PHPExcel_Writer_Excel5($PHPExcel);
$string = range('A', 'Z');
//写入数据
foreach ($array as $key=>$value) {
//输入第一列
$PHPExcel->getActiveSheet()->setCellValue($string[0].$key, $key);
//输入第二列
$PHPExcel->getActiveSheet()->setCellValue($string[1].$key, $value);
}
//保存到xls
$PHPExcel_write->save('15/city.xls');
如题2: 纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示:
写入到student.xls文件中:
{
"1":["张三",150,120,100],
"2":["李四",90,99,95],
"3":["王五",60,66,68]
}
代码为:
<?php
/**
* 把txt中的json数据导入到excel中
* Created by PhpStorm.
* User: Administrator
* Date: 2016/12/9
* Time: 19:02
*/
require_once 'Common/PHPExcel/Classes/PHPExcel.php';
//读取文件并且转json为数组
$json = file_get_contents('14/student.txt');
$array = json_decode($json, true);
$PHPExcel = new PHPExcel();
$PHPExcel_write = new PHPExcel_Writer_Excel5($PHPExcel);
$string = range('A', 'Z');
//写入数据
foreach ($array as $key=>$value) {
//输入第一列
$PHPExcel->getActiveSheet()->setCellValue($string[0].$key, $key);
//输入后面的列
foreach ($value as $key2=>$value2) {
$PHPExcel->getActiveSheet()->setCellValue($string[$key2+1].$key, $value2);
}
}
//保存到xls
$PHPExcel_write->save('14/student.xls');
如题3: 读取execl文件
代码为:
<?php
/**
* 将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中
* Created by PhpStorm.
* User: Administrator
* Date: 2016/12/17
* Time: 21:38
*/
require_once 'Common\PHPExcel\Classes\PHPExcel\IOFactory.php';
$reader = PHPExcel_IOFactory::createReader('Excel5'); //设置以Excel5格式(Excel97-2003工作簿)
$PHPExcel = $reader->load("17/student.xls"); // 载入excel文件
$sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumm = $sheet->getHighestColumn(); // 取得总列数
/** 循环读取每个单元格的数据 */
for ($row = 1; $row <= $highestRow; $row++){//行数是以第1行开始
for ($column = 'B'; $column <= $highestColumm; $column++) {//列数是以B列开始
$dataset[$row][] = $sheet->getCell($column.$row)->getValue();
}
}
var_dump($dataset);