function BuildReportTable($startColumn, $startRow)
{
    global $dataConnector;
    global $objPhpExcel;
    global $billingItemArray;
    global $salesPerson;
    global $model;
    global $searchMethod;
    $billingItemDAO = new BillingItemDAO($dataConnector->mysqlConnection);
    $billingItemDAO->showErrors = 1;
    $equipmentDAO = new EquipmentDAO($dataConnector->sqlserverConnection);
    $equipmentDAO->showErrors = 1;
    $equipmentModelDAO = new EquipmentModelDAO($dataConnector->mysqlConnection);
    $equipmentModelDAO->showErrors = 1;
    $manufacturerDAO = new ManufacturerDAO($dataConnector->sqlserverConnection);
    $manufacturerDAO->showErrors = 1;
    $counterDAO = new CounterDAO($dataConnector->mysqlConnection);
    $counterDAO->showErrors = 1;
    $salesPersonDAO = new SalesPersonDAO($dataConnector->sqlserverConnection);
    $salesPersonDAO->showErrors = 1;
    // Define o titulo da tabela
    $currentRow = $startRow;
    $activeSheet = $objPhpExcel->getActiveSheet();
    $activeSheet->setCellValue($startColumn . $startRow, 'ITENS DE FATURAMENTO');
    $styleArray = array('font' => array('bold' => true, 'size' => 16));
    $activeSheet->getStyle($startColumn . $startRow . ':' . $startColumn . $startRow)->applyFromArray($styleArray);
    // Cria o cabeçalho da tabela
    $colNum = ord($startColumn) - 65;
    // startColumn é uma letra no intervalo A-Z
    $headers = array('Cliente', 'Descrição Equipamento', 'Modelo', 'Fabricante', 'Série Fabricante', 'Nosso Núm. Série', 'Data Instalação', 'Inicio Atendimento', 'Fim Atendimento', 'Medidor', 'Data Leitura', 'Medição Final', 'Medição Inicial', 'Ajuste Medição(Acrésc/Desc)', 'Consumo', 'Franquia', 'Excedente', 'Tarifa sobre exced.', 'Fixo (R$)', 'Variável (R$)', 'Acrésc/Desc (R$)', 'Total (R$)', 'Parcela Atual', 'Vendedor');
    $offset = 0;
    foreach ($headers as $header) {
        $activeSheet->getColumnDimension(GetNameFromNumber($colNum + $offset))->setWidth(30);
        $offset++;
    }
    $currentRow++;
    InsereLinhaPlanilha($currentRow, $startColumn, $headers, PHPExcel_Style_Color::COLOR_YELLOW, 30, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    // Busca os fabricantes cadastrados no sistema
    $manufacturerArray = array(0 => "");
    $tempArray = $manufacturerDAO->RetrieveRecordArray();
    foreach ($tempArray as $manufacturer) {
        $manufacturerArray[$manufacturer->FirmCode] = $manufacturer->FirmName;
    }
    // Busca os modelos de equipamento cadastrados no sistema
    $modelArray = array(0 => "");
    $equipmentModelArray = $equipmentModelDAO->RetrieveRecordArray();
    foreach ($equipmentModelArray as $modelDTO) {
        $modelArray[$modelDTO->id] = $modelDTO->modelo;
    }
    $associativeList = array(0 => "");
    foreach ($equipmentModelArray as $modelDTO) {
        $associativeList[$modelDTO->id] = $manufacturerArray[$modelDTO->fabricante];
    }
    // Busca os contadores cadastrados no sistema
    $retrievedArray = $counterDAO->RetrieveRecordArray();
    $counterArray = array();
    foreach ($retrievedArray as $counter) {
        $counterArray[$counter->id] = $counter->nome;
    }
    // Busca os vendedores cadastrados no sistema
    $retrievedArray = $salesPersonDAO->RetrieveRecordArray();
    $salesPersonArray = array();
    foreach ($retrievedArray as $salesPersonDTO) {
        $salesPersonArray[$salesPersonDTO->slpCode] = $salesPersonDTO->slpName;
    }
    // Gera as linhas da tabela
    $grandTotal = 0;
    foreach ($billingItemArray as $billingItem) {
        $equipment = $equipmentDAO->RetrieveRecord($billingItem->codigoCartaoEquipamento);
        $contractCoveragePeriod = ContractDAO::GetContractCoveragePeriod($dataConnector->mysqlConnection, $billingItem->contrato_id);
        $inicioAtendimento = isset($contractCoveragePeriod) ? $contractCoveragePeriod["inicioAtendimento"] : '';
        $fimAtendimento = isset($contractCoveragePeriod) ? $contractCoveragePeriod["fimAtendimento"] : '';
        $parcelaAtual = isset($contractCoveragePeriod) ? $contractCoveragePeriod["parcelaAtual"] : '';
        $receitaTotal = $billingItem->total + $billingItem->acrescimoDesconto;
        if ($salesPerson > 0) {
            if ($equipment->salesPerson != $salesPerson) {
                continue;
            }
        }
        if ($searchMethod == 1 || $searchMethod == 2) {
            if (!empty($model)) {
                $modelMatched = false;
                if (strpos($equipment->itemName, $model)) {
                    $modelMatched = true;
                }
                if (!$modelMatched) {
                    continue;
                }
            }
        }
        $installationDate = empty($equipment->installationDate) ? '' : $equipment->installationDate->format('d/m/Y');
        $salesPersonCode = $equipment->salesPerson;
        if (empty($salesPersonCode)) {
            $salesPersonCode = -1;
        }
        $salesPersonName = $salesPersonArray[$salesPersonCode];
        $currentRow++;
        $row = array();
        $row[0] = $equipment->custmrName;
        $row[1] = $equipment->itemName;
        $row[2] = $modelArray[$equipment->model];
        $row[3] = $associativeList[$equipment->model];
        // Recupera o fabricante do modelo de equipamento
        $row[4] = $equipment->manufacturerSN;
        $row[5] = $equipment->internalSN;
        $row[6] = $installationDate;
        $row[7] = $inicioAtendimento;
        $row[8] = $fimAtendimento;
        $row[9] = $counterArray[$billingItem->counterId];
        $row[10] = $billingItem->dataLeitura;
        $row[11] = $billingItem->medicaoFinal;
        $row[12] = $billingItem->medicaoInicial;
        $row[13] = $billingItem->ajuste;
        $row[14] = $billingItem->consumo;
        $row[15] = $billingItem->franquia;
        $row[16] = $billingItem->excedente;
        $row[17] = number_format($billingItem->tarifaSobreExcedente, 6, ',', '.');
        $row[18] = number_format($billingItem->fixo, 2, ',', '.');
        $row[19] = number_format($billingItem->variavel, 2, ',', '.');
        $row[20] = number_format($billingItem->acrescimoDesconto, 2, ',', '.');
        $row[21] = number_format($receitaTotal, 2, ',', '.');
        $row[22] = $parcelaAtual;
        $row[23] = $salesPersonName;
        InsereLinhaPlanilha($currentRow, $startColumn, $row);
        $grandTotal += $receitaTotal;
        // Soma a receita total do equipamento ( fixo mais variável )
    }
    $currentRow++;
    $total = array('Total da Receita: ' . number_format($grandTotal, 2, ',', '.'), '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0');
    InsereLinhaPlanilha($currentRow, $startColumn, $total, '80BB80FF', 45, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $activeSheet->mergeCells(GetNameFromNumber($colNum + 0) . $currentRow . ':' . GetNameFromNumber($colNum + sizeof($headers) - 1) . $currentRow);
}
function BuildReportTable($startColumn, $startRow)
{
    global $root;
    global $dataConnector;
    global $objPhpExcel;
    global $billingItemArray;
    $businessPartnerDAO = new BusinessPartnerDAO($dataConnector->sqlserverConnection);
    $businessPartnerDAO->showErrors = 1;
    $industryDAO = new IndustryDAO($dataConnector->sqlserverConnection);
    $industryDAO->showErrors = 1;
    $equipmentDAO = new EquipmentDAO($dataConnector->sqlserverConnection);
    $equipmentDAO->showErrors = 1;
    $equipmentModelDAO = new EquipmentModelDAO($dataConnector->mysqlConnection);
    $equipmentModelDAO->showErrors = 1;
    $manufacturerDAO = new ManufacturerDAO($dataConnector->sqlserverConnection);
    $manufacturerDAO->showErrors = 1;
    $contractDAO = new ContractDAO($dataConnector->mysqlConnection);
    $contractDAO->showErrors = 1;
    $inventoryItemDAO = new InventoryItemDAO($dataConnector->sqlserverConnection);
    $inventoryItemDAO->showErrors = 1;
    $counterDAO = new CounterDAO($dataConnector->mysqlConnection);
    $counterDAO->showErrors = 1;
    $salesPersonDAO = new SalesPersonDAO($dataConnector->sqlserverConnection);
    $salesPersonDAO->showErrors = 1;
    // Busca os segmentos/ramos de atividade cadastrados no sistema
    $industryArray = array(0 => "");
    $tempArray = $industryDAO->RetrieveRecordArray();
    foreach ($tempArray as $industry) {
        $industryArray[$industry->id] = $industry->name;
    }
    // Busca os fabricantes cadastrados no sistema
    $manufacturerArray = array(0 => "");
    $tempArray = $manufacturerDAO->RetrieveRecordArray();
    foreach ($tempArray as $manufacturer) {
        $manufacturerArray[$manufacturer->FirmCode] = $manufacturer->FirmName;
    }
    // Busca os modelos de equipamento cadastrados no sistema
    $modelArray = array(0 => "");
    $equipmentModelArray = $equipmentModelDAO->RetrieveRecordArray();
    foreach ($equipmentModelArray as $modelDTO) {
        $modelArray[$modelDTO->id] = $modelDTO->modelo;
    }
    // Cria um array para as estatísticas dos equipamentos (por modelo)
    $statsArray = array();
    $equipmentModelArray = $equipmentModelDAO->RetrieveRecordArray("id > 0 ORDER BY fabricante, modelo");
    foreach ($equipmentModelArray as $modelDTO) {
        $statsArray[$modelDTO->id] = new EquipmentModelStats($modelDTO->id, $modelDTO->modelo, $modelDTO->fabricante);
    }
    // Cria um array para as receitas de cada equipamento
    $equipRevenueArray = array();
    // Cria um array para as receitas provenientes de cada cliente
    $customerRevenueArray = array();
    $associativeList = array(0 => "");
    foreach ($equipmentModelArray as $model) {
        $associativeList[$model->id] = $manufacturerArray[$model->fabricante];
    }
    // Busca os contadores cadastrados no sistema
    $retrievedArray = $counterDAO->RetrieveRecordArray();
    $counterArray = array();
    foreach ($retrievedArray as $counter) {
        $counterArray[$counter->id] = $counter->nome;
    }
    // Busca os vendedores cadastrados no sistema
    $retrievedArray = $salesPersonDAO->RetrieveRecordArray();
    $salesPersonArray = array();
    foreach ($retrievedArray as $salesPersonDTO) {
        $salesPersonArray[$salesPersonDTO->slpCode] = $salesPersonDTO->slpName;
    }
    // Define o titulo da tabela
    $currentRow = $startRow;
    $activeSheet = $objPhpExcel->getActiveSheet();
    $activeSheet->setCellValue($startColumn . $startRow, 'SÍNTESE POR EQUIPAMENTO');
    $styleArray = array('font' => array('bold' => true, 'size' => 16));
    $activeSheet->getStyle($startColumn . $startRow . ':' . $startColumn . $startRow)->applyFromArray($styleArray);
    // Cria o cabeçalho da tabela
    $colNum = ord($startColumn) - 65;
    // startColumn é uma letra no intervalo A-Z
    $headers = array('Cliente', 'Segmento', 'Modelo', 'Fabricante', 'Série Fabricante', 'Nosso Núm. Série', 'Obs. Item', 'Data Instalação', 'Inicio Atendimento', 'Fim Atendimento', 'Parcela Atual', 'Vendedor', 'Medidor', 'Data Leitura', 'Medição Final', 'Medição Inicial', 'Ajuste Medição(Acrésc/Desc)', 'Consumo', 'Franquia', 'Excedente (Págs.)', 'Tarifa sobre exced.', 'Valor Fixo (R$)', 'Valor Variável (R$)', 'Acrésc/Desc (R$)', 'Valor Total (R$)', 'Custo Aquisição', 'Vida Útil', 'Custo Pág. do Equip.', 'Custo Pág. Peças/Mat.', 'Custo Pág. Total', 'Custo/Receita', 'Despesas');
    $offset = 0;
    foreach ($headers as $header) {
        $activeSheet->getColumnDimension(GetNameFromNumber($colNum + $offset))->setWidth(30);
        $offset++;
    }
    $currentRow++;
    InsereLinhaPlanilha($currentRow, $startColumn, $headers, PHPExcel_Style_Color::COLOR_YELLOW, 30, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    // Gera as linhas da tabela
    $totalFixo = 0;
    $totalVariavel = 0;
    $totalAcrescDesc = 0;
    $grandTotal = 0;
    foreach ($billingItemArray as $billingItem) {
        $equipment = $equipmentDAO->RetrieveRecord($billingItem->codigoCartaoEquipamento);
        $businessPartner = $businessPartnerDAO->RetrieveRecord($equipment->customer);
        $contractCoveragePeriod = ContractDAO::GetContractCoveragePeriod($dataConnector->mysqlConnection, $billingItem->contrato_id);
        $installationDate = empty($equipment->installationDate) ? '' : $equipment->installationDate->format('d/m/Y');
        $inicioAtendimento = isset($contractCoveragePeriod) ? $contractCoveragePeriod["inicioAtendimento"] : '';
        $fimAtendimento = isset($contractCoveragePeriod) ? $contractCoveragePeriod["fimAtendimento"] : '';
        $parcelaAtual = isset($contractCoveragePeriod) ? $contractCoveragePeriod["parcelaAtual"] : '';
        $receitaTotal = $billingItem->total + $billingItem->acrescimoDesconto;
        $inventoryItem = $inventoryItemDAO->RetrieveRecord($equipment->itemCode);
        $obsItem = $inventoryItem->userText;
        $custoAquisicao = $inventoryItem->avgPrice;
        $custoPagPecas = $inventoryItem->expenses;
        $vidaUtil = $inventoryItem->durability;
        if (empty($vidaUtil)) {
            $custoPagEquip = 0;
            $custoTotal = 0;
            $custoSobreReceita = 0;
        } else {
            $custoPagEquip = $custoAquisicao / $vidaUtil * 1.4;
            $custoTotal = ($custoPagEquip + $custoPagPecas) * $billingItem->consumo;
            $custoSobreReceita = 0;
            if ($receitaTotal != 0) {
                $custoSobreReceita = $custoTotal / $receitaTotal;
            }
        }
        // Busca os dados do vendedor
        $salesPersonCode = $equipment->salesPerson;
        if (empty($salesPersonCode)) {
            $salesPersonCode = -1;
        }
        $salesPersonName = $salesPersonArray[$salesPersonCode];
        // Busca os dados do segmento/ramo de atividade
        $industryCode = $businessPartner->industry;
        if (empty($industryCode)) {
            $industryCode = 0;
        }
        $industryName = $industryArray[$industryCode];
        // Busca o modelo e fabricante do equipamento
        $modelName = "";
        if (array_key_exists($equipment->model, $modelArray)) {
            $modelName = $modelArray[$equipment->model];
        }
        $manufacturerName = "";
        if (array_key_exists($equipment->model, $modelArray)) {
            $manufacturerName = $associativeList[$equipment->model];
        }
        if (!array_key_exists($equipment->manufacturerSN, $equipRevenueArray)) {
            $equipRevenueArray[$equipment->manufacturerSN] = new EquipmentRevenue($equipment->manufacturerSN, $equipment->model, $modelName, $manufacturerName, 0);
        }
        $equipRevenue = $equipRevenueArray[$equipment->manufacturerSN];
        $equipRevenue->revenue += $receitaTotal;
        if (!array_key_exists($equipment->customer, $customerRevenueArray)) {
            $customerRevenueArray[$equipment->customer] = new CustomerRevenue($equipment->customer, 0);
        }
        $customerRevenue = $customerRevenueArray[$equipment->customer];
        $customerRevenue->revenue += $receitaTotal;
        $row = array();
        $row[0] = $businessPartner->cardName . ' (' . $businessPartner->cardCode . ')';
        $row[1] = $industryName;
        $row[2] = $modelName;
        $row[3] = $manufacturerName;
        $row[4] = $equipment->manufacturerSN;
        $row[5] = $equipment->internalSN;
        $row[6] = $obsItem;
        $row[7] = $installationDate;
        $row[8] = $inicioAtendimento;
        $row[9] = $fimAtendimento;
        $row[10] = $parcelaAtual;
        $row[11] = $salesPersonName;
        $row[12] = $counterArray[$billingItem->counterId];
        // Recupera o nome do medidor/contador
        $row[13] = $billingItem->dataLeitura;
        $row[14] = $billingItem->medicaoFinal;
        $row[15] = $billingItem->medicaoInicial;
        $row[16] = $billingItem->ajuste;
        $row[17] = $billingItem->consumo;
        $row[18] = $billingItem->franquia;
        $row[19] = $billingItem->excedente;
        $row[20] = formatDecimal($billingItem->tarifaSobreExcedente, null);
        $row[21] = formatBrCurrency($billingItem->fixo, 2);
        $row[22] = formatBrCurrency($billingItem->variavel, 2);
        $row[23] = formatBrCurrency($billingItem->acrescimoDesconto, 2);
        $row[24] = formatBrCurrency($receitaTotal, 2);
        $row[25] = formatBrCurrency($custoAquisicao, 2);
        $row[26] = $vidaUtil;
        $row[27] = formatDecimal($custoPagEquip, 6);
        $row[28] = formatDecimal($custoPagPecas, 6);
        $row[29] = formatBrCurrency($custoTotal, 2);
        $row[30] = formatDecimal($custoSobreReceita, 6);
        $row[31] = 'http://datadb/contratos/AjaxCalls/GetEquipmentExpenses.php?equipmentCode=' . $equipment->insID . '&billingId=' . $billingItem->codigoFaturamento . '&showDetails=true';
        $currentRow++;
        InsereLinhaPlanilha($currentRow, $startColumn, $row);
        $totalFixo += $billingItem->fixo;
        // Soma os valores fixos dos equipamentos
        $totalVariavel += $billingItem->variavel;
        // Soma os valores variáveis dos equipamentos
        $totalAcrescDesc += $billingItem->acrescimoDesconto;
        // Soma os acrescimos descontos dos equipamentos
        $grandTotal += $receitaTotal;
        // Soma a receita total dos equipamentos ( fixo mais variável )
    }
    $currentRow++;
    $summary = array('Quant. Clientes: ' . sizeof($customerRevenueArray), '', '', '', 'Quant. Equipamentos: ' . sizeof($equipRevenueArray), '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'Total Fixo: ' . number_format($totalFixo, 2, ',', '.'), 'Total Variável: ' . number_format($totalVariavel, 2, ',', '.'), 'Total Acrésc/Desc: ' . number_format($totalAcrescDesc, 2, ',', '.'), 'Total Receita: ' . number_format($grandTotal, 2, ',', '.'), '', '', '', '', '', '', '');
    InsereLinhaPlanilha($currentRow, $startColumn, $summary, '80BB80FF', 32, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    foreach ($equipRevenueArray as $equipRevenue) {
        if (array_key_exists($equipRevenue->modelId, $statsArray)) {
            $modelStats = $statsArray[$equipRevenue->modelId];
            $modelStats->revenue += $equipRevenue->revenue;
            $modelStats->equipmentCount += 1;
        }
    }
    $currentRow += 3;
    // pula 3 linhas
    $startColumn = 'G';
    // fixa o quadro resumo na setima coluna da planilha
    // Define o titulo do quadro resumo
    $activeSheet = $objPhpExcel->getActiveSheet();
    $activeSheet->setCellValue($startColumn . $currentRow, 'QUADRO RESUMO');
    $styleArray = array('font' => array('bold' => true, 'size' => 16));
    $activeSheet->getStyle($startColumn . $currentRow . ':' . $startColumn . $currentRow)->applyFromArray($styleArray);
    // Cria o cabeçalho do quadro resumo
    $colNum = ord($startColumn);
    $headers = array('Modelo', 'Fabricante', 'Quantidade', 'Receita');
    $offset = 0;
    foreach ($headers as $header) {
        $activeSheet->getColumnDimension(chr($colNum + $offset))->setWidth(25);
        $offset++;
    }
    $currentRow++;
    InsereLinhaPlanilha($currentRow, $startColumn, $headers, PHPExcel_Style_Color::COLOR_YELLOW, 30, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $valorPrevio = "";
    $equipCount = 0;
    $somaReceita = 0;
    foreach ($statsArray as $equipmentModelStats) {
        if ($equipmentModelStats->equipmentCount > 0) {
            $manufacturerName = $manufacturerArray[$equipmentModelStats->fabricante];
            $valorAtual = $manufacturerName;
            if ($valorPrevio != $valorAtual) {
                if (!empty($valorPrevio)) {
                    $subTotal = array('', '', $equipCount, number_format($somaReceita, 2, ',', '.'));
                    $currentRow++;
                    InsereLinhaPlanilha($currentRow, $startColumn, $subTotal, '80AAFFFF', 20, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $equipCount = 0;
                    $somaReceita = 0;
                }
                $valorPrevio = $valorAtual;
            }
            $currentRow++;
            $row = array();
            $row[0] = $equipmentModelStats->model;
            $row[1] = $manufacturerName;
            $row[2] = $equipmentModelStats->equipmentCount;
            $row[3] = number_format($equipmentModelStats->revenue, 2, ',', '.');
            InsereLinhaPlanilha($currentRow, $startColumn, $row);
            $equipCount = $equipCount + $equipmentModelStats->equipmentCount;
            $somaReceita = $somaReceita + $equipmentModelStats->revenue;
        }
    }
    $subTotal = array('', '', $equipCount, number_format($somaReceita, 2, ',', '.'));
    $currentRow++;
    InsereLinhaPlanilha($currentRow, $startColumn, $subTotal, '80AAFFFF', 20, PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
}