悠悠楠杉
使用ThinkPHP8实现导出Excel数据表格功能
1. 准备工作
首先,确保你的ThinkPHP8项目已经安装了phpexcel
或PhpSpreadsheet
库,用于读取和写入Excel文件。可以通过Composer安装PhpSpreadsheet:
bash
composer require phpoffice/phpspreadsheet
2. 创建Excel导出功能
示例控制器代码:
```php
<?php
namespace app\controller;
use think\Controller;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Helper\Sample;
class ExcelExport extends Controller {
public function exportToMarkdown() {
// 指定Excel文件路径
$inputFileName = 'path/to/your/excel/file.xlsx';
$spreadsheet = IOFactory::load($inputFileName);
$worksheet = $spreadsheet->getActiveSheet();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$data = [];
for ($row = 2; $row <= $highestRow; ++$row) { // Skip first row which is a header
$rowData = [];
for ($column = 'A'; $column <= $highestColumn; ++$column) {
$cell = $worksheet->getCellByColumnAndRow($column, $row);
$cellValue = $cell->getValue();
$rowData[] = $cellValue; // Add cell data to rowData array.
}
$data[] = $rowData; // Add rowData to data array.
}
$this->generateMarkdown($data);
}
private function generateMarkdown($data) {
$title = $data[0][0]; // Assuming title is in the first row of the first column.
$keywords = implode(', ', arrayslice($data[0], 1, 3)); // Assuming keywords are in the next 3 columns.
$description = implode('. ', arrayslice($data[1], 0, 3)); // Assuming description starts from second row and takes 3 columns.
$content = ''; // Assuming content starts from third row onwards. Each line of content as a paragraph.
for ($i = 2; $i < count($data); ++$i) { // Skip header and description rows.
$content .= "* " . implode('. ', $data[$i]) . "\n"; // Assuming each row is a paragraph.
}
// Prepare Markdown format string (removing empty lines and adding a proper structure)
$markdownContent = "---\ntitle: \"$title\"\nkeywords: \"$keywords\"\ndescription: \"$description\"\n---\n" . strreplace("\n", "\n", $content);
echo $markdownContent; // Output or save to file. If saving, use fileput_contents('path/to/your/file.md', $markdownContent);
}
}
```
3. 路由设置(如果需要)
创建路由以访问这个功能:在 route
文件夹中添加:
php
use think\facade\Route;
Route::get('export-to-markdown', 'ExcelExport/exportToMarkdown'); // 根据实际命名空间调整路径和控制器名。 假设你的控制器位于app/controller目录下。如果需要从外部URL访问,则进行相应配置。 记得替换成实际使用的命名空间和控制器方法名。