Introdução
A Classe NfsReport foi criada com o objetivo de abstrair a crição de Planilhas Eletrônicas e manter as práticas correntes desse processo no NFS.
Criar e Manipular Planilha
/**
* Cria objeto NfsReport permintindo o preenchimento e formatação.
*
* @param array $options Opções da planilha
* $options = [
* 'title' => ?string = 'título do documento'
* 'subject' => ?string = 'assunto do documento'
* 'sheetName' => ?string = 'nome da planilha'
* 'userName' => ?string = 'nome do usuário'
* ];
*/
public static function createSpreadsheet(array $options): self
/**
* Cria uma nova aba em uma Planilha.
*
* @param string $sheetName Nome da aba / worksheet
* @param int $index Índice da aba / worksheet
*/
public function createSheet(string $sheetName, int $index = 0): self
/**
* Define planilha ativa por índice.
*
* @param int $index Índice da planilha (começa no 0)
*/
public function setActiveSheetByIndex(int $index): self
/**
* Define planilha ativa pelo nome da planilha.
*
* @param string $name Nome da planilha
*/
public function setActiveSheetByName(string $name): self
/**
* Define o título da planilha.
*
* @param string $title Título da planilha
*/
public function setTitle(string $title): self
/**
* Finaliza objeto e libera recursos alocados.
*/
public function close()
Manipulação de Dados
/**
* Define valor de uma célula.
*
* @param string $cell Referência da Célula [A1|..|ZN]
* @param mixed $value Valor da célula
* @param string $dataType Tipo de dado (Referência Constantes Tipos de Dado)
*/
public function setCellValue(string $cell, mixed $value, ?string $dataType = null): self
/**
* Preenche planilha com valores do array.
*
* @param array $rows Dados a adicionar
* @param string $cell Célula de referência para preenchimento
*/
public function addFromArray(array $rows, string $cell = 'A1'): self
/**
* Mescla celulas e preenche.
*
* @param string $reference Referência para mesclagem e preenchimento
* @param mixed $value Valor de preenchimento da célula mesclada
* @param mixed $wrapText Se o valor aceita quebra de linha ou não
*/
public function mergeCells(string $reference, mixed $value = null, bool $wrapText = true): self
/**
* Define explicitamento o tipo de dados de uma célula.
*
* @param string $cell Referência da célula
* @param string $dataType $dataType Tipo de dado
*/
public function setCellDataType(string $cell, string $dataType): self
/**
* Define a formatação de campos/bloco de células.
* IMPORTANTE: usar a string do formato, não as constantes definidas na classe.
*
* @param string $reference Referência da célula ('A1'..'Z9'|) ou bloco ('A1:C3'..'A1:Z5')
* @param string $format String do formato (Referência Constantes Tipos de Dado)
*/
public function setNumberFormat(string $reference, string $format): self
/**
* Insere imagem vinculada a uma célula.
*
* @param string $base64 Base64 da imagem que será inserida
* @param string $reference Referência da célula
* @param null|array $props Propriedades da imagem
* [height, width, name, description, offSetX, offSetY, rotation]
*/
public function addImageFromBase64(string $base64, string $reference, ?array $props = []): self
Formatação de Dados
/**
* Define largura da coluna.
*
* @param string $col Referência da coluna (A..Z..AA..ZZ)
* @param float $width Largura relativa ao tamanho da fonte
*/
public function setColWidth(string $col, float $width): self
/**
* Define altura da linha.
*
* @param int $row Referência da linha
* @param float $height Altura da linha relativa ao tamanho da fonte
*/
public function setRowHeight(int $row, float $height): self
/**
* Define referência para aplicação de propriedades.
*
* @param string $reference Célula ou bloco de células
*/
public function getStyle(string $reference): self
/**
* Aplica estilos usando array de propriedades.
* IMPORTANTE: usar a string do formato, não as constantes definidas na classe.
* Usar as strings definidas em cada propriedade (de acordo com os métodos dessa classe).
*
* @param array $props Propriedades definidas (Referência Externa Estilos)
*/
public function applyFromArray(array $props): self
/**
* Define o alinhamento da célula ou celulas.
*
* @param string $reference Referência para mesclagem e preenchimento
* @param string $horAlign Alinhamento horizontal (Referência Constantes Alinhamento Horizontal)
* @param string $vertAlign Alinhamento vertical (Referência Constantes Alinhamento Vertical)
* @param bool $wrapText Se o valor aceita quebra de linha ou não
*/
public function setAlignment($reference, $horAlign = 'general', $vertAlign = 'v-top', $wrapText = false): self
/**
* Define formatação da célula ou células.
*
* @param string $reference Referência para mesclagem e preenchimento
* @param float $fontSize Tamanho da fonte
* @param string $fontColor Cor da fonte
* @param bool $fontBold Se o texto estará em negrito ou não
* @param bool $fontItalic Se o texto estará em itálico ou não
* @param string $bgColor Cor de fundo / background
*/
public function setStyle(string $reference, float $fontSize = 11, ?string $fontColor = null, bool $fontBold = false, bool $fontItalic = false, ?string $bgColor = null): self
/**
* Tenta determinar a largura de uma coluna
* Se o parâmetro não for especificado, define autosize para todas as colunas preenchidas.
*
* @param string $col Referência da coluna (A-Z..AA..ZZ)
*/
public function autoSize(?string $col = null): self
/**
* Define célula/bloco como.
*
* @param string $reference Referência célula/bloco
* @param bool $prop Se o valor aceita quebra de linha ou não
*/
public function setWrapText(string $reference, bool $prop = true): self
Quando se exporta o crud list num excel os campos LOVN são exibidos juntos, para facilitar a quebra de linha foi criado o parâmetro CRUD_LIST_LOVN_LINE_BREAK para fazer o parse no excel.
CRUD_LIST_LOVN_LINE_BREAK
Referências
Constantes Definidas
Tipo de Preenchimento de Cor de Fundo / Background
Opções: 'none', 'solid', 'linear'
Alinhamento
Opções Horizontal: 'general', 'left', 'right', 'center', 'justify'
Opções Vertical: 'v-top', 'v-center', 'v-bottom', 'v-justify'
Tipos de Dado
Opções: 'string', 'formula', 'numeric', 'boolean', 'null', 'inline', 'error'
Tipos de Borda
Opções: 'none', 'dashDot', 'dashDotDot', 'dashed', 'dotted', 'double', 'hair', 'medium', 'mediumDashDot', 'mediumDashDotDot', 'mediumDashed', 'slantDashDot', 'thick', 'thin'
Fontes Sublinhadas / Underline
Opções: 'none', 'double', 'single'
Referências Externas
- Classe Base PhpSpreadsheet{target=_blank}.
- Formatos de Número{target=_blank}
- Definição de Estilos{target=_blank}
IMPORTANTE: nos relatórios gerados através da tabela nfs_reports o nome do objeto criado pelo processo foi definido como
$sheet
(na versão antiga era$objPHPExcel
). {.is-warning}
Casos de Uso
Criação e Preenchimento
$report = NfsReport::createSpreadsheet([
'title' => 'Planilha',
'subject' => 'Teste de classe NfsReport',
'userName' => 'Teste Unitário',
'sheetName' => 'Planilha Teste',
]);
$report->addFromArray([
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
], 'A1');
$report->CreateSheet('Planilha 2', 1);
$report->addFromArray([
['Core', 'Dev', 'Support'],
['Simova', 'NFS', 'Report'],
], 'A1');
$report->setActiveSheetByIndex(0);
$report->addFromArray([
['Core', 'Dev', 'Support'],
['Simova', 'NFS', 'Report'],
], 'A5');
Criação, Preenchimento e Formatação
$report = NfsReport::createSpreadsheet([
'title' => 'Planilha',
'subject' => 'Teste de classe NfsReport',
'userName' => 'Teste Unitário',
]);
$report->addFromArray([
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
], 'A1');
$report->getStyle('A1:E1')
->applyFromArray([
'fill' => [
'fillType' => 'solid',
'color' => [
'rgb' => 'FF0000',
],
],
'font' => [
'name' => 'Calibri',
'bold' => true,
'underline' => 'double',
'color' => [
'rgb' => 'FFFFFF',
],
'size' => 14.5,
],
'borders' => [
'allBorders' => [
'borderStyle' => 'double',
'color' => [
'argb' => '000000',
],
],
],
'alignment' => [
'horizontal' => 'center',
'vertical' => 'v-center',
'wrapText' => true,
],
'quotePrefix' => true,
]);
$report->getStyle('A2:E2')
->applyFromArray([
'fill' => [
'fillType' => 'solid',
'color' => [
'rgb' => '00FF83',
],
],
'font' => [
'name' => 'Arial',
'bold' => true,
'italic' => true,
'superscript' => true,
'underline' => 'single',
'strikethrough' => true,
'color' => [
'rgb' => '808080',
],
'size' => 11,
],
'borders' => [
'allBorders' => [
'borderStyle' => 'dashDot',
'color' => [
'rgb' => 'f9a11a',
],
],
],
'alignment' => [
'horizontal' => 'center',
'vertical' => 'v-center',
'wrapText' => true,
],
'quotePrefix' => true,
]);
$report->getStyle('A3:E4')
->applyFromArray([
'font' => [
'name' => 'Tahoma',
'superscript' => true,
'color' => [
'rgb' => 'FF000000',
],
'size' => 8,
],
]);
Outro Exemplo
$display_name = 'MSI';
$sheet = NfsReport::createSpreadsheet([
'title' => $display_name,
'subject' => $display_name,
'sheetName' => $display_name
]);
$row = 1;
$styleTitleCenter = [
'font' => [
'size' => 12,
'bold' => true,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'FFFFFF']
],
'alignment' => [
'horizontal' => 'center',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'FFFFFF']
]
]
];
$styleTitleLeft = [
'font' => [
'size' => 12,
'bold' => true,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'FFFFFF']
],
'alignment' => [
'horizontal' => 'left',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'FFFFFF']
]
]
];
$styleTitleRight = [
'font' => [
'size' => 12,
'bold' => true,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'FFFFFF']
],
'alignment' => [
'horizontal' => 'right',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'FFFFFF']
]
]
];
$styleHeadCenterBlue = [
'font' => [
'size' => 11,
'bold' => true,
'color' => ['rgb' => 'FFFFFF']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => '002060']
],
'alignment' => [
'horizontal' => 'center',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => '002060']
]
]
];
$styleHeadLeftBlue = [
'font' => [
'size' => 11,
'bold' => true,
'color' => ['rgb' => 'FFFFFF']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => '002060']
],
'alignment' => [
'horizontal' => 'left',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => '002060']
]
]
];
$styleHeadRightBlue = [
'font' => [
'size' => 11,
'bold' => true,
'color' => ['rgb' => 'FFFFFF']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => '002060']
],
'alignment' => [
'horizontal' => 'right',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => '002060']
]
]
];
$styleHeadCenterPurple = [
'font' => [
'size' => 11,
'bold' => true,
'color' => ['rgb' => 'FFFFFF']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => '421c5e']
],
'alignment' => [
'horizontal' => 'center',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => '421c5e']
]
]
];
$styleHeadLeftPurple = [
'font' => [
'size' => 11,
'bold' => true,
'color' => ['rgb' => 'FFFFFF']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => '421c5e']
],
'alignment' => [
'horizontal' => 'left',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => '421c5e']
]
]
];
$styleHeadRightPurple = [
'font' => [
'size' => 11,
'bold' => true,
'color' => ['rgb' => 'FFFFFF']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => '421c5e']
],
'alignment' => [
'horizontal' => 'right',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => '421c5e']
]
]
];
$styleCenterWhite = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'FFFFFF']
],
'alignment' => [
'horizontal' => 'center',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'FFFFFF']
]
]
];
$styleLeftWhite = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'FFFFFF']
],
'alignment' => [
'horizontal' => 'left',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'FFFFFF']
]
]
];
$styleRightWhite = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'FFFFFF']
],
'alignment' => [
'horizontal' => 'right',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'FFFFFF']
]
]
];
$styleCenterBlue = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'dae3f3']
],
'alignment' => [
'horizontal' => 'center',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'dae3f3']
]
]
];
$styleLeftBlue = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'dae3f3']
],
'alignment' => [
'horizontal' => 'left',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'dae3f3']
]
]
];
$styleRightBlue = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'dae3f3']
],
'alignment' => [
'horizontal' => 'right',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'dae3f3']
]
]
];
$styleLightBlue = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'dae3f3']
],
'alignment' => [
'horizontal' => 'right',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'dae3f3']
]
]
];
$styleDarkBlue = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'b4c7e7']
],
'alignment' => [
'horizontal' => 'right',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'b4c7e7']
]
]
];
$styleCenterPurple = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'ccccff']
],
'alignment' => [
'horizontal' => 'center',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'ccccff']
]
]
];
$styleLeftPurple = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'ccccff']
],
'alignment' => [
'horizontal' => 'left',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'ccccff']
]
]
];
$styleRightPurple = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'ccccff']
],
'alignment' => [
'horizontal' => 'right',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'ccccff']
]
]
];
$styleLightPurple = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => 'ccccff']
],
'alignment' => [
'horizontal' => 'right',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => 'ccccff']
]
]
];
$styleDarkPurple = [
'font' => [
'size' => 11,
'bold' => false,
'color' => ['rgb' => '000000']
],
'fill' => [
'fillType' => 'solid',
'color' => ['rgb' => '9b9bff']
],
'alignment' => [
'horizontal' => 'right',
'vertical' => 'v-center'
],
'borders' => [
'allBorders' => [
'borderStyle' => 'thin',
'color' => ['rgb' => '9b9bff']
]
]
];
foreach (range('A','X') as $column) {
$sheet->getColumnDimension($column)->setAutoSize(true);
}
foreach ($templateData['projeto_list'] as $s) {
$sheet->getStyle("A{$row}")->applyFromArray($styleTitleLeft);
$sheet->getStyle("B{$row}:I{$row}")->applyFromArray($styleTitleCenter);
$sheet->SetCellValue("A{$row}", 'DISCIPLINA');
$sheet->SetCellValue("B{$row}", 'PROJETO');
$sheet->SetCellValue("C{$row}", 'ÁREA');
$sheet->SetCellValue("D{$row}", 'SEMANA');
$sheet->SetCellValue("E{$row}", 'INFORMAÇÃO');
$sheet->SetCellValue("F{$row}", 'PROGRAMAÇÃO');
$sheet->SetCellValue("G{$row}", 'MEDIÇÃO');
$sheet->SetCellValue("H{$row}", 'Cód');
$sheet->SetCellValue("I{$row}", 'Unid.');
$row ++;
foreach ($templateData['processo_list'][$s['CHAVE']] as $p) {
$tipo_processo = $p['TIPO_PROCESSO'];
$styleHeadCenter = $styleHeadCenterBlue;
$styleHeadLeft = $styleHeadLeftBlue;
$styleHeadRight = $styleHeadRightBlue;
if ($tipo_processo == '1') {
$styleHeadCenter = $styleHeadCenterBlue;
$styleHeadLeft = $styleHeadLeftBlue;
$styleHeadRight = $styleHeadRightBlue;
} else {
$styleHeadCenter = $styleHeadCenterPurple;
$styleHeadLeft = $styleHeadLeftPurple;
$styleHeadRight = $styleHeadRightPurple;
}
$sheet->getStyle("A{$row}:I{$row}")->applyFromArray($styleHeadCenter);
$sheet->getStyle("A{$row}")->applyFromArray($styleHeadLeft);
$sheet->SetCellValue("A{$row}", $p['DISCIPLINA']);
$sheet->SetCellValue("B{$row}", $p['PROJETO']);
$sheet->getStyle("C{$row}")->applyFromArray($styleHeadLeft);
$sheet->SetCellValue("C{$row}", $p['AREA']);
$sheet->SetCellValue("D{$row}", $p['SEMANA']);
$sheet->getStyle("E{$row}")->applyFromArray($styleHeadLeft);
$sheet->SetCellValue("E{$row}", $p['INFORMACAO']);
$sheet->getStyle("F{$row}:G{$row}")->applyFromArray($styleHeadRight);
$sheet->SetCellValue("F{$row}", $p['PROGRAMACAO']);
$sheet->SetCellValue("G{$row}", $p['MEDICAO']);
$sheet->SetCellValue("H{$row}", $p['CODIGO']);
$sheet->SetCellValue("I{$row}", $p['UNIDADE']);
$row++;
foreach ($templateData['modulo_list'][$p['CHAVE']] as $m) {
$styleCenter = $styleCenterWhite;
$styleLeft = $styleLeftWhite;
$styleRight = $styleLightBlue;
if ($tipo_processo == '1') {
if (($row%2) == 1) {
$styleCenter = $styleCenterWhite;
$styleLeft = $styleLeftWhite;
$styleRight = $styleLightBlue;
} else {
$styleCenter = $styleCenterBlue;
$styleLeft = $styleLeftBlue;
$styleRight = $styleDarkBlue;
}
} else {
if (($row%2) == 1) {
$styleCenter = $styleCenterWhite;
$styleLeft = $styleLeftWhite;
$styleRight = $styleLightBlue;
} else {
$styleCenter = $styleCenterPurple;
$styleLeft = $styleLeftPurple;
$styleRight = $styleDarkPurple;
}
}
$sheet->getStyle("A{$row}:I{$row}")->applyFromArray($styleCenter);
$sheet->getStyle("A{$row}")->applyFromArray($styleLeft);
$sheet->SetCellValue("A{$row}", $m['DISCIPLINA']);
$sheet->SetCellValue("B{$row}", $m['PROJETO']);
$sheet->getStyle("C{$row}")->applyFromArray($styleLeft);
$sheet->SetCellValue("C{$row}", $m['AREA']);
$sheet->SetCellValue("D{$row}", $m['SEMANA']);
$sheet->getStyle("E{$row}")->applyFromArray($styleLeft);
$sheet->SetCellValue("E{$row}", $m['INFORMACAO']);
$sheet->getStyle("F{$row}:G{$row}")->applyFromArray($styleRight);
$sheet->SetCellValue("F{$row}", $m['PROGRAMACAO']);
$sheet->SetCellValue("G{$row}", $m['MEDICAO']);
$sheet->SetCellValue("H{$row}", $m['CODIGO']);
$sheet->SetCellValue("I{$row}", $m['UNIDADE']);
$row++;
}
$row++;
}
$row++;
}