天天看點

php excel轉html,PHP-上傳excel轉換HTML輸出

php excel轉html,PHP-上傳excel轉換HTML輸出

image

這個方法是借助phpoffice/phpexcel來完成的,話不多說,我們直接上碼

public function excelToHtml()

{

return $this->apiSuc(ActionExcel::excel2html(request()->file()));

}

public static function excel2html($data)

{

$obj = $data['file'];

//上傳檔案

$info = $obj->move(ROOT_PATH . 'public' . DS . 'uploads'. DS . 'file');

$filePath = $info->getPathname();

$externsion = $info->getExtension();

$fileFullName = $info->getFilename();

$htmlName = str_replace('.' . $externsion, '', $fileFullName);

//檔案名自動判斷檔案類型

$fileType = PHPExcel_IOFactory::identify($filePath);

$objReader = PHPExcel_IOFactory::createReader($fileType);

$objPHPExcel = $objReader->load($filePath);

$sheetIndex = $objPHPExcel->getSheetCount();

$objWriter = new PHPExcel_Writer_HTML($objPHPExcel);

//可以将括号中的0換成需要操作的sheet索引

$sheetHtml = [];

for ($i = 0;$i < $sheetIndex;$i++) {

//這裡記得将檔案名包含進去

$savePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'html' . DS . $htmlName . '_' . ($i+1) . '.html';

$objWriter->setSheetIndex($i);

//儲存為html檔案

$objWriter->save($savePath);

$downloadPath = config('setting.site_url') . '/uploads/html/'. $htmlName . '_' . ($i+1) . '.html';

array_push($sheetHtml, $downloadPath);

}

return $sheetHtml;

}

這裡是內建在thinkphp5中的寫法,其他架構或者直接原生代碼,實作的邏輯都是一樣的.那麼我們再次梳理一遍

1. 上傳檔案

2. 讀取檔案

3. 寫入HTML檔案

4. 輸出新的HTML檔案