Skip to content

Instantly share code, notes, and snippets.

@haxianhe
Created January 7, 2021 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haxianhe/2ea550d1837fa416f83d9f119660a7b5 to your computer and use it in GitHub Desktop.
Save haxianhe/2ea550d1837fa416f83d9f119660a7b5 to your computer and use it in GitHub Desktop.
csv处理函数
<?php
/**
* @Desc: csv处理函数
* @User: haxianhe
* @Date: 2019/4/2
* @Time: 5:03 PM
*/
abstract class CSV
{
protected $file;
/**
* @desc 连续创建目录
* @param $dir
* @param int $mode
* @return bool
*/
protected function makeDir($dir, $mode = 0755)
{
if (empty($dir)) {
return false;
}
if (!file_exists($dir)) { //如果目录不存在,则创建目录
return mkdir($dir, $mode, true);
} else {
return true;
}
}
/**
* @desc 清空文件夹函数和清空文件夹后删除空文件夹函数的处理
* @param $path
*/
protected function delDir($path)
{
//如果是目录则继续
if (is_dir($path)) {
//扫描一个文件夹内的所有文件夹和文件并返回数组
$p = scandir($path);
foreach ($p as $val) {
//排除目录中的.和..
if ($val != "." && $val != "..") {
//如果是目录则递归子目录,继续操作
if (is_dir($path . $val)) {
//子目录中操作删除文件夹和文件
deldir($path . $val . '/');
//目录清空后删除空文件夹
rmdir($path . $val . '/');
} else {
//如果是文件直接删除
unlink($path . $val);
}
}
}
}
}
/**
* 导出excel(csv)
* @data 导出数据
* @headlist 第一行,列名
* @fileName 输出Excel文件名
*/
protected function csv_export($data = array(), $headlist = array(), $fileName)
{
$fp = fopen(__DIR__ . "/excel/$fileName.csv", 'a');
//输出Excel列名信息
foreach ($headlist as $key => $value) {
//CSV的Excel支持GBK编码,一定要转换,否则乱码
$headlist[$key] = iconv('utf-8', 'gbk', $value);
}
//将数据通过fputcsv写到文件句柄
fputcsv($fp, $headlist);
$count = count($data);
for ($i = 0; $i < $count; $i++) {
$row = $data[$i];
foreach ($row as $key => $value) {
$row[$key] = iconv('utf-8', 'gbk', $value);
}
fputcsv($fp, $row);
}
fclose($fp);
return true;
}
/**
* @desc 倒入excel(csv)
* @return array excel内容
*/
protected function csv_import()
{
$file = $this->file;
$handle = fopen($file, 'r');
$excelContent = [];
if ($handle !== false){
while ($data = fgetcsv($handle)) { //每次读取CSV里面的一行内容
// $data = eval('return '.iconv('gbk','utf-8',var_export($data,true)).';');
$excelContent[] = $data;
}
fclose($handle);
}
return $excelContent;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment