Skip to content

Commit

Permalink
Excel拓展类
Browse files Browse the repository at this point in the history
  • Loading branch information
dashingunique committed Jun 23, 2020
1 parent 300c2ea commit 4b656d6
Show file tree
Hide file tree
Showing 7 changed files with 730 additions and 22 deletions.
24 changes: 2 additions & 22 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,23 +1,3 @@
/vendor/
node_modules/
npm-debug.log
yarn-error.log

# Laravel 4 specific
bootstrap/compiled.php
app/storage/

# Laravel 5 & Lumen specific
public/storage
public/hot

# Laravel 5 & Lumen specific with changed public path
public_html/storage
public_html/hot

storage/*.key
.env
Homestead.yaml
Homestead.json
/.vagrant
.phpunit.result.cache
/.idea
composer.lock
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,54 @@
# excel
Excel import/export for Php

Install via composer:

```
composer require dashingunique/excel
```
## 导出文件信息

将文件导出到 `.csv`(.xlsx .obs) 文件:

```php
use dashingunique\excel\DashingExcel;
use app\model\User;

// Load users
$users = new User()->select();
$users = uniqueCollection($users);
// Export all users
(new DashingExcel($users))->export('file.csv');
```


仅导入指定信息的列
```php
$users = new User()->select();
$users = uniqueCollection($users);
(new DashingExcel($users))->export('users.csv', function ($user) {
return [
'Email' => $user['email'],
'First Name' => $user['firstname'],
'Last Name' => strtotime($user['create_time']),
];
});
```

## 导入文件信息

导入文件信息
```php
$collection = (new DashingExcel())->configureCsv(';', '#', '\n', 'gbk')->import('file.csv');
```

导入文件并写入数据库
```php
$users = (new DashingExcel())->import('file.xlsx', function ($line) {
return (new User())->create([
'name' => $line['Name'],
'email' => $line['Email']
]);
});
```

30 changes: 30 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "dashingunique/excel",
"type": "library",
"keywords": ["excel", "csv", "xls", "xlsx"],
"description": "Excel import/export for php",
"require": {
"php": "^7.1",
"box/spout": "^2.7",
"dashingunique/library": "^1.0"
},
"autoload": {
"psr-4": {
"dashingunique\\excel\\": "src/"
},
"files": [
"src/Helpers.php"
]
},
"extra": {
},
"license": "MIT",
"authors": [
{
"name": "dashingunique",
"email": "1107842285@qq.com"
}
],
"minimum-stability": "dev",
"prefer-stable": true
}
187 changes: 187 additions & 0 deletions src/DashingExcel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
<?php

namespace dashingunique\excel;

use Box\Spout\Common\Type;
use Box\Spout\Reader\CSV\Reader as CSVReader;
use Box\Spout\Reader\ReaderInterface;
use Box\Spout\Writer\CSV\Writer as CSVWriter;
use Box\Spout\Writer\WriterInterface;
use dashingunique\excel\traits\Exportable;
use dashingunique\excel\traits\ImportData;
use dashingunique\library\Collection;
use dashingunique\library\Str;

/**
* Excel操作类
* Class DashingExcel
* @package dashingunique\excel
*/
class DashingExcel
{
use ImportData;
use Exportable;

/**
* @var Collection
*/
protected $data;

/**
* @var bool
*/
protected $withHeader = true;

/**
* @var
*/
private $csvConfig = [
'delimiter' => ',',
'enclosure' => '"',
'eol' => "\n",
'encoding' => 'UTF-8',
'bom' => true,
];

/**
* @var callable
*/
protected $readerConfigurator = null;

/**
* @var callable
*/
protected $writerConfigurator = null;

/**
* DashingExcel constructor.
* @param Collection $data
*/
public function __construct($data = null)
{
$this->data = $data;
}

/**
* 设置数据信息
* @param $data
* @return $this
*/
public function data($data)
{
$this->data = $data;
return $this;
}

/**
* 获取文件后缀名
* @param $path
* @return string
*/
protected function getType($path)
{
if (Str::endsWith($path, Type::CSV)) {
return Type::CSV;
} elseif (Str::endsWith($path, Type::ODS)) {
return Type::ODS;
} else {
return Type::XLSX;
}
}

/**
* 设置单元格数量
* @param $sheetNumber
* @return $this
*/
public function sheet($sheetNumber)
{
$this->sheetNumber = $sheetNumber;

return $this;
}

/**
* 不需要header信息
* @return $this
*/
public function withoutHeaders()
{
$this->withHeader = false;
return $this;
}

/**
* 配置CSV信息
* @param string $delimiter
* @param string $enclosure
* @param string $eol
* @param string $encoding
* @param bool $bom
*
* @return $this
*/
public function configureCsv($delimiter = ',', $enclosure = '"', $eol = "\n", $encoding = 'UTF-8', $bom = false)
{
$this->csvConfig = compact('delimiter', 'enclosure', 'eol', 'encoding', 'bom');

return $this;
}

/**
* 使用回调配置基础的读取阅读器。
*
* @param callable $callback
*
* @return $this
*/
public function configureReaderUsing(?callable $callback = null)
{
$this->readerConfigurator = $callback;

return $this;
}

/**
* 使用回调配置基础的写入阅读器。
* @param callable $callback
*
* @return $this
*/
public function configureWriterUsing(?callable $callback = null)
{
$this->writerConfigurator = $callback;
return $this;
}

/**
* 设置读写信息
* @param ReaderInterface|WriterInterface $readerOrWriter
*/
protected function setOptions(&$readerOrWriter)
{
if ($readerOrWriter instanceof CSVReader || $readerOrWriter instanceof CSVWriter) {
$readerOrWriter->setFieldDelimiter($this->csvConfig['delimiter']);
$readerOrWriter->setFieldEnclosure($this->csvConfig['enclosure']);
if ($readerOrWriter instanceof CSVReader) {
$readerOrWriter->setEndOfLineCharacter($this->csvConfig['eol']);
$readerOrWriter->setEncoding($this->csvConfig['encoding']);
}
if ($readerOrWriter instanceof CSVWriter) {
$readerOrWriter->setShouldAddBOM($this->csvConfig['bom']);
}
}

if ($readerOrWriter instanceof ReaderInterface && is_callable($this->readerConfigurator)) {
call_user_func(
$this->readerConfigurator,
$readerOrWriter
);
} elseif ($readerOrWriter instanceof WriterInterface && is_callable($this->writerConfigurator)) {
call_user_func(
$this->writerConfigurator,
$readerOrWriter
);
}
}
}
18 changes: 18 additions & 0 deletions src/Helpers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

use dashingunique\library\Collection;
use dashingunique\excel\DashingExcel;

if (!function_exists('DashingExcel')) {
/**
* @param null $data
* @return DashingExcel
*/
function DashingExcel($data = null)
{
if (is_object($data) && method_exists($data, 'toArray')) {
$data = $data->toArray();
}
return blank($data) ? new DashingExcel() : new DashingExcel($data);
}
}
Loading

0 comments on commit 4b656d6

Please sign in to comment.