sugangqiang 2 年之前
父节点
当前提交
5f464501ee
共有 1 个文件被更改,包括 54 次插入10 次删除
  1. 54 10
      app/common.php

+ 54 - 10
app/common.php

@@ -81,18 +81,62 @@ function getExcelDatas($filepath, $sheetIndex = 0) {
     return $sheet->toArray();
 }
 
-
 /**
- * 
+ * 导出excel
  * @param type $title 标题
- * @param type $data 数据
- * @param type $detail 抬头内容 array(array(),array())
+ * @param type $columns 列标题
+ * @param type $rows 内容
  * @param string $filename 文件名
- * @param type $format 数字格式化
- * @param type $saveurl 输出方式
+ * @param type $saveurl 保存位置
  * @param type $author 作者
  */
-function export($title, $data, $detail = null, $filename = "g2beauty", $freeze = null, $format = [], $saveurl = "php://output", $other_config = null, $author = "g2beauty.cn") {
+function export($title, $columns, $rows, $filename = "jjrcw", $saveurl = "php://output", $author = "晋江人才网") {
+    $filename .= "_" . time();
+    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
+    $spreadsheet->getProperties()->setCreator($author)
+            ->setLastModifiedBy($author)
+            ->setTitle($filename)
+            ->setSubject($filename);
+    $spreadsheet->setActiveSheetIndex(0);
+    $objPHPExcel = $spreadsheet->getActiveSheet();
+    $objPHPExcel->setTitle($title);
+    $titleStartLine = 1;
+    $rowStartLine = $titleStartLine + 1;
+    $colCount = count($columns);
+    $rowCount = count($rows);
+    //设置表头
+    for ($i = 0; $i < $colCount; $i++) {
+        $objPHPExcel->setCellValue(getExcelColumnByIndex($i) . $titleStartLine, $columns[$i]);
+    }
+    //设置正文内容
+    for ($i = 0; $i < $rowCount; $i++) {
+        for ($n = 0; $n < $colCount; $n++) {
+            $objPHPExcel->setCellValue(getExcelColumnByIndex($n) . ($rowStartLine + $i), $rows[$i][$n]);
+        }
+    }
+
+    header('Content-Type: application/vnd.ms-excel');
+    header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
+    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
+    $writer->save($saveurl);
+    //删除临时的sheet
+    $spreadsheet->disconnectWorksheets();
+    unset($spreadsheet);
+    exit;
+}
+
+/**
+ * 根据传入的数值(游标),从26个英文字母的数组中查询,返回excel列标
+ * @param int $index 游标从0开始
+ * @return string 返回列标
+ */
+function getExcelColumnByIndex(int $index) {
+    $letters = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
+    if ($letters[$index])
+        return $letters[$index];
+    $rowIndex = floor($index / 26) - 1;
+    $colIndex = $index % 26;
+    return $letters[$rowIndex] . $letters[$colIndex];
 }
 
 /**
@@ -119,9 +163,9 @@ function isExcelFile($mime) {
  * @param $path
  * @return string
  */
-function getStoragePath($path){
-    if($path){
+function getStoragePath($path) {
+    if ($path) {
         return "/storage/{$path}";
     }
     return "";
-}
+}