Página 1 de 2

Planilha XML padrão Excel

Enviado: 13 Set 2023 08:09
por clodoaldomonteiro
Olá.

Depois de um tempo procurando exportar meus relatórios para Excel, tentando com DLLs, "CreateObject( "ADODB.Connection" )" ou "CreateObject( "Excel.Application" )", achei uma forma fácil, rápida e sem a dependência de soluções de terceiros, que foi escrever um XML com o padrão que o Excel salva as planilha formato: "Planilha XML 2003 (*.xml)".

O Arquivo salvo nesse formato, nada mais é que um texto no padrão XML, criando ExcelWorkbook, Styles, Worksheet, Table, Column, Row, Cell e etc.

Qualquer um pode fazer o teste, abrindo o Excel, colocando algo nas células e salvando no formato XML aqui indicado, e aí vai ver como é registrado os dados, Fontes, Tamanhos de células, Fórmulas, Cores e por ai vai.

Não vou me estender muito e logo abaixo colocarei os fonte de como eu fiz, que é bem simples mesmo, pra todos verem e possam usar e contribuir.

Exemplo Main()

Código: Selecionar todos

Function Mail()

   ...
   ...

   aTabela := {}

   Use <tabela>
   Set Filter ...

   Do While !Eof()
      ...
      ...
      ...
      
      If mExportarToExcel = 'S' //Adiciona as Rows da tabale
         AAdd( aTabela, {;
          Transform(qdd_uo, '@R 99.99.99'),;
          Trim(TUO->TUO_titulo),;
          qdd_fg,;
          qdd_SF,;
          qdd_pg,;
          Transform(tpa_pa, '@R 9.999'),;
          AlLTrim(TPA->TPA_titulo),;
          qdd_ficha,;
          Transform(qdd_ed, "@R 99.99.99"),;
          Trim(TED->ted_titulo),;
          qdd_fr,;
          Trim( cl_ItemArray( aFROrigem, qdd_fr, 2) ),;
          vl_fixatu  ,;
          mSupAnu    ,;
          mValor1    ,;
          mValor2    ,;
          hSaldo     ;
          })
      Endif
      ...
      ...
      ...
      
      Skip

   Enddo

   Use

   If mExportarToExcel = 'S'

      aCabecalho := {;  //Monta o cabeçalho da tabela com Descriçào e largura da célula
       {"U.O."          , 047},;
       {"U.O. Descri‡Æo", 200},;
       {"F.G."          , 047},;
       {"Sub F.G."      , 047},;
       {"P.G."          , 047},;
       {"A‡Æo C¢digo"   , 047},;
       {"A‡Æo Descri‡Æo", 200},;
       {"Ficha N£mero"  , 047},;
       {"Elemento C¢digo"     , 047},;
       {"Elemento Descri‡Æo"  , 200},;
       {"F.R. C¢digo"         , 047},;
       {"F.R. Descri‡Æo"      , 200},;
       {"Valor Fixado"        , 070},;
       {"Suplementado/Anulado", 070},;
       {"Empenhado At‚ Mˆs"   , 070},;
       {"Previsto Final Ano"  , 070},;
       {"Saldo Atual"         , 070};
       }

      If xmlGeraTabela(mArqXls, 'FichaDota‡Æo', aCabecalho, aTabela, 'Demonstrativo da Fixa‡Æo da Despesa e PrevisÆo para o resto do ano')

         msg := 'O arquivo XLS(' + mArqXls + ') foi criado com sucesso. '
         msg += CRLF+ 'Deseja abri-lo?'

         If MsgYesNo( msg )
            AbreArquivo( mArqXls )
         EndIf

      Endif

   EndIf
   
   ...
   ...

   Return nil
Funções para criar o arquivo XML:

Código: Selecionar todos

////////////////////////////////////////////////////////////////////////////////
/*
Funções pafa Gerar XML e salvar como .xls pra ler no Excel

-Exemplo de aCabecalho{}:
aCabecalho := {;
 {"Data"          , 047},;
 {"DIA C¢digo"    , 047},;
 {"CAP C¢digo"    , 047},;
 {"PCASP Conta"   , 070},;
 {"Hist¢rico"     , 200},;
 {"Documento"     , 100},;
 {"U.O"           , 047},;
 {"Fonte Recurso" , 047},;
 {"Valor D‚bito"  , 070},;
 {"Valor Cr‚dito" , 070},;
 {"Saldo"         , 070};
 }

-Exemplo de registro SaldoInicial em aTabela{}:
AAdd( aTabela, {;   //Linha de Totais
 '01/' + pe_mm,;
 'Saldo inicial',;
 'Conta origem -->',;
 Transform(aDados[i, 4], '@R 99999.99.99'),;
 aDados[i, 5],;
 Trim(cl_ItemArray(aTipoContaBancaria, aDados[i, 21], 2))+;
 ", Banco: " + aDados[i, 1] + ', Agˆncia: ' + aDados[i, 2]  +;
 ', Conta Banc ria: ' + Transform(aDados[i, 3], '@R 999.999.999.999'),;
 '',;          //UO
 '',;          //FR
 '',;          //D‚bito
 '',;          //Cr‚dito
 {'Saldo', aDados[i, 6]}; //Saldo
 })

-Exemplo de registro TotalFinal em aTabela{}:
AAdd( aTabela, {;   //Linha de Totais
 'éltimo dia',;
 '',;
 '',;
 '',;
 'TOTAL DA CONTA BANCµRIA: Qtd - ' + Str(i, 5),;
 '',;
 '',;
 '',;
 {'Total', TDebSLD},;
 {'Total', TCreSLD},;
 {'Total', mSaldo};
 })

-Exemplo de Hash com fórmula para coluna de aTabela{}.
hSaldo := {;
 "Formula" => '=RC[-4]+RC[-3]-RC[-2]',;
 "Number"  => vl_fixatu + mSupAnu - mValor1 }
*/
////////////////////////////////////////////////////////////////////////////////

//#pragma -w0
//#pragma -es0

//#include "hbcompat.ch"

#define CRLF  Chr(13)+Chr(10)

MemVar M_VERSAO, userName, nEmp

//////////////////////////////////////////////////////////////////////////////////
//FUNCOES PARA GERAR XLS
Function xmlGeraTabela(cFile, cWorksheetName, aCabecalho, aTabela, cRelName)
   Local nHandle, r, nLenTabela := Len(aTabela) + 5

   nHandle := xmlOpenBook(cFile, cWorksheetName, aCabecalho, nLenTabela, cRelName )

   xmlWriteRow(nHandle, aTabela )

   xmlRodape( nHandle, nLenTabela, Len(aCabecalho) -1 )

   r := xmlClose( nHandle )

   Return r

Function xmlAjustaString( cString )

   cString := AllTrim( cString )
   cString := StrTran( cString, CRLF, ' ' )
   cString := StrTran( cString, Chr(10), ' ' )
   cString := StrTran( cString, Chr(13), ' ' )
   cString := StrTran( cString, Chr(141), ' ' )
   cString := hb_strToUTF8( cString )

   Return cString

Function xmlRodape(nHandle, nLenTabela, nLenCabecalho)
   LOCAL mRow, nMergeLeft := Int( nLenCabecalho / 2), nMergeRight := nLenCabecalho - nMergeLeft -1

   mRow := [   <Row ss:Index="] + LTrim(Str(nLenTabela)) + [" ss:AutoFitHeight="0">] + CRLF

   mRow += '    <Cell ss:MergeAcross="' + LTrim(Str(nMergeLeft)) + '" ss:StyleID="CellRodapeLeft">' +;
    '<Data ss:Type="String">'+ hb_strToUTF8('Usu rio: ' + AlLTrim(userName) ) +;
    ' | Data: ' + TtoC(DateTime()) + ' | SIAFIC: SCP21H / Ver: ' + M_VERSAO +;
    ' / File: ' + ProcFile(2) + '</Data></Cell>' + CRLF

   mRow += '    <Cell ss:MergeAcross="' + LTrim(Str(nMergeRight)) +;
    '" ss:StyleID="CellRodapeRight" ss:HRef="https://www.simplesinformatica.com.br/">' +;
    '<Data ss:Type="String">www.SimplesInformatica.com.br</Data></Cell>' + CRLF

   mRow += [   </Row>] + CRLF

   FWrite(nHandle, mRow, Len(mRow))

   Return nMergeRight

   /////////////////////////////////////////////////////////////////////////////
   //Para Cell com Formula, usa-se ss:Formula.
   // - Ex.: col D [= A + B - C]. Levanta-se a array RC[x], onde seria o valor da posição de D - a posição da col a ser usada.
   // - Explicando RC[] (R = Row e C = Col)
   // - Ficando: < ... ss:Formula="=RC[-4]+RC[-3]-RC[-2]"><Data ...
FUNCTION xmlWriteRow(nHandle, aTabela )
   LOCAL mRow, i, x

   For i := 1 TO Len(aTabela)
      mRow := [   <Row ss:AutoFitHeight="0">] + CRLF

      For x := 1 To Len(aTabela[i])

         If Valtype(aTabela[i, x]) = 'N'
            mRow += [    <Cell ss:StyleID="ValorContabil"><Data ss:Type="Number">] + LTrim(Str(aTabela[i, x], 11,2)) + [</Data></Cell>] + CRLF

         ElseIf Valtype(aTabela[i, x]) = 'A'
            If aTabela[i, x, 1] = 'Saldo'
               mRow += [    <Cell ss:StyleID="CellSaldo"><Data ss:Type="Number">] + LTrim(Str(aTabela[i, x, 2], 11,2)) + [</Data></Cell>] + CRLF

            ElseIf aTabela[i, x, 1] = 'Total'
               mRow += [    <Cell ss:StyleID="CellTotal"><Data ss:Type="Number">] + LTrim(Str(aTabela[i, x, 2], 11,2)) + [</Data></Cell>] + CRLF

            Else
               mRow += [    <Cell ss:StyleID="ValorContabil"><Data ss:Type="Number">] + LTrim(Str(aTabela[i, x], 11,2)) + [</Data></Cell>] + CRLF

            Endif

         ElseIf Valtype(aTabela[i, x]) = 'H'
            mRow += [    <Cell ss:StyleID="ValorContabil" ss:Formula="] + aTabela[i, x]["Formula"] +["><Data ss:Type="Number">] + LTrim(Str(aTabela[i, x]["Number"], 11,2)) + [</Data></Cell>] + CRLF

         Else
            mRow += [    <Cell><Data ss:Type="String" x:Ticked="1">] + xmlAjustaString( aTabela[i, x] ) + [</Data></Cell>] + CRLF

         Endif
      Next

      mRow += [   </Row>] + CRLF

      FWrite(nHandle, mRow, Len(mRow))

   Next nI

   RETURN nil

   /////////////////////////////////////////////////////////////////////////////
   //Largura padrão das cell é 47, definido em <Column ss:Index="1" ss:AutoFitWidth="0" ss:Width="47"/>
   //"ExpandedColumnCount" registra a quantidade de colunas da tabela
FUNCTION xmlOpenBook(cFile, cWorksheetName, aCabecalho, nRowCount, cRelName)
   LOCAL nHandle, mBof := '', i
   Local nMergeLeft := Int( (Len(aCabecalho) -1) / 2), nMergeRight := (Len(aCabecalho) -1) - nMergeLeft -1

   mBof += [<!--SimplesInformatica.com.br-->] + CRLF

   mBof += [<?xml version="1.0"?>] + CRLF
   mBof += [<?mso-application progid="Excel.Sheet"?>] + CRLF
   mBof += [<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"] + CRLF
   mBof += [ xmlns:o="urn:schemas-microsoft-com:office:office"] + CRLF
   mBof += [ xmlns:x="urn:schemas-microsoft-com:office:excel"] + CRLF
   mBof += [ xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"] + CRLF
   mBof += [ xmlns:html="http://www.w3.org/TR/REC-html40">] + CRLF
   mBof += [ <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">] + CRLF
   mBof += [  <Version>12.00</Version>] + CRLF
   mBof += [ </DocumentProperties>] + CRLF

   mBof += [ <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">] + CRLF
   mBof += [  <WindowHeight>10005</WindowHeight>] + CRLF
   mBof += [  <WindowWidth>10005</WindowWidth>] + CRLF
   mBof += [  <WindowTopX>120</WindowTopX>] + CRLF
   mBof += [  <WindowTopY>135</WindowTopY>] + CRLF
   mBof += [  <ProtectStructure>False</ProtectStructure>] + CRLF
   mBof += [  <ProtectWindows>False</ProtectWindows>] + CRLF
   mBof += [ </ExcelWorkbook>] + CRLF

   mBof += [ <Styles>] + CRLF

   mBof += [  <Style ss:ID="Default" ss:Name="Normal">] + CRLF
   mBof += [   <Alignment ss:Vertical="Bottom"/>] + CRLF
   mBof += [   <Borders/>] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"/>] + CRLF
   mBof += [   <Interior/>] + CRLF
   mBof += [   <NumberFormat/>] + CRLF
   mBof += [   <Protection/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CellCabeca">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#EAF1DD" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="ValorContabil">] + CRLF
   mBof += '   <NumberFormat ss:Format="#,##0.00_ ;[Red]\-#,##0.00\ "/>' + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CellSaldo">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#E5E0EC" ss:Pattern="Solid"/>] + CRLF
   mBof += '   <NumberFormat ss:Format="[Blue]#,##0.00_ ;[Red]\-#,##0.00\ "/>' + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CellTotal">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#D8D8D8" ss:Pattern="Solid"/>] + CRLF
   mBof += '   <NumberFormat ss:Format="[Blue]#,##0.00_ ;[Red]\-#,##0.00\ "/>' + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CellRodapeLeft">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   //mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="9" ss:Color="#4F6228" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#D8D8D8" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="s74" ss:Name="Hyperlink">] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#0000FF" ss:Underline="Single"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CellRodapeRight" ss:Parent="s74">] + CRLF
   mBof += [   <Alignment ss:Horizontal="Right" ss:Vertical="Bottom"/>] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   //mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   //mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#4F6228" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#D8D8D8" ss:Pattern="Solid"/>] + CRLF
   mBof += [   <Protection/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CabecalhoLeftTop">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Times New Roman" x:Family="Roman" ss:Size="14" ss:Color="#000000" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#DBEEF3" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CabecalhoLeftBottom">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Times New Roman" x:Family="Roman" ss:Size="13" ss:Color="#000000" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#DBEEF3" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CabecalhoRightTop">] + CRLF
   mBof += [   <Alignment ss:Horizontal="Right" ss:Vertical="Bottom"/>] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Interior ss:Color="#DBEEF3" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CabecalhoRightBottom">] + CRLF
   mBof += [   <Alignment ss:Horizontal="Right" ss:Vertical="Bottom"/>] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Interior ss:Color="#DBEEF3" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [ </Styles>] + CRLF

   mBof += [ <Worksheet ss:Name="] + hb_strToUTF8(cWorksheetName) + [">] + CRLF

   mBof += [  <Table ss:ExpandedColumnCount="] + LTrim(Str(Len(aCabecalho))) + [" ss:ExpandedRowCount="] + LTrim(Str(nRowCount)) + [" x:FullColumns="1" x:FullRows="1" ss:DefaultRowHeight="15">] + CRLF

   For i := 1 To Len(aCabecalho)
      mBof += [   <Column ss:Index="] + LTrim(Str(i)) + [" ss:AutoFitWidth="0" ss:Width="] + LTrim(Str(aCabecalho[i, 2])) + ["/>] + CRLF
   Next

   mBof += [   <Row ss:AutoFitHeight="0" ss:Height="19">] + CRLF
   mBof += [    <Cell ss:MergeAcross="] + LTrim(Str(nMergeLeft)) +;
    [" ss:StyleID="CabecalhoLeftTop"><Data ss:Type="String">] + xmlAjustaString( nEmp ) + [</Data></Cell>] + CRLF
   mBof += [    <Cell ss:MergeAcross="] + LTrim(Str(nMergeRight)) +;
    [" ss:StyleID="CabecalhoRightTop"><Data ss:Type="String">Top</Data></Cell>] + CRLF
   mBof += [   </Row>] + CRLF

   mBof += [   <Row ss:AutoFitHeight="0" ss:Height="19">] + CRLF
   mBof += [    <Cell ss:MergeAcross="] + LTrim(Str(nMergeLeft)) +;
    [" ss:StyleID="CabecalhoLeftBottom"><Data ss:Type="String">] + xmlAjustaString( cRelName ) + [</Data></Cell>] + CRLF
   mBof += [    <Cell ss:MergeAcross="] + LTrim(Str(nMergeRight)) +;
    [" ss:StyleID="CabecalhoRightBottom"><Data ss:Type="String">Valores em (R$)</Data></Cell>] + CRLF
   mBof += [   </Row>] + CRLF

   mBof += [   <Row ss:AutoFitHeight="0">] + CRLF
   For i := 1 To Len(aCabecalho)
      mBof += [    <Cell ss:Index="] + LTrim(Str(i)) + [" ss:StyleID="CellCabeca"><Data ss:Type="String">] + hb_strToUTF8( aCabecalho[i, 1] ) + [</Data></Cell>] + CRLF
   Next
   mBof += [   </Row>] + CRLF

   nHandle := FCreate(cFile)
   FWrite(nHandle, mBof, Len(mBof))

   RETURN nHandle


   /////////////////////////////////////////////////////////////////////////////
   //Fecha e grava o arquivo.
   //Retorna True se tudo der certo e False caso tenha acontecido algum erro ao gravar.
   //FError() pode ser usado para conferir o erro
FUNCTION xmlClose( nHandle )
   LOCAL mEof := '', r := .t.

   mEof += [  </Table>] + CRLF

   mEof += [  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">] + CRLF

   mEof += [   <PageSetup>] + CRLF
   mEof += [    <Header x:Margin="0.4921259845"/>] + CRLF
   mEof += [    <Footer x:Margin="0.4921259845"/>] + CRLF
   mEof += [    <PageMargins x:Bottom="0.984251969" x:Left="0.78740157499999996" x:Right="0.78740157499999996" x:Top="0.984251969"/>] + CRLF
   mEof += [   </PageSetup>] + CRLF

   mEof += [   <Unsynced/>] + CRLF

   mEof += [   <Print>] + CRLF
   mEof += [    <ValidPrinterInfo/>] + CRLF
   mEof += [    <PaperSizeIndex>9</PaperSizeIndex>] + CRLF
   mEof += [    <HorizontalResolution>600</HorizontalResolution>] + CRLF
   mEof += [    <VerticalResolution>600</VerticalResolution>] + CRLF
   mEof += [   </Print>] + CRLF

   mEof += [   <Selected/>] + CRLF

   mEof += [   <FreezePanes/>] + CRLF     //Congela a primeira linha
   mEof += [   <FrozenNoSplit/>] + CRLF
   mEof += [   <SplitHorizontal>3</SplitHorizontal>] + CRLF
   mEof += [   <TopRowBottomPane>3</TopRowBottomPane>] + CRLF
   mEof += [   <ActivePane>2</ActivePane>] + CRLF

   mEof += [   <Panes>] + CRLF
   mEof += [    <Pane>] + CRLF
   mEof += [     <Number>3</Number>] + CRLF
   mEof += [    </Pane>] + CRLF
   mEof += [    <Pane>] + CRLF
   mEof += [     <Number>2</Number>] + CRLF
   mEof += [     <ActiveCol>1</ActiveCol>] + CRLF
   mEof += [    </Pane>] + CRLF
   mEof += [   </Panes>] + CRLF

   mEof += [   <ProtectObjects>False</ProtectObjects>] + CRLF
   mEof += [   <ProtectScenarios>False</ProtectScenarios>] + CRLF

   mEof += [  </WorksheetOptions>] + CRLF

   mEof += [ </Worksheet>] + CRLF

   mEof += [</Workbook>]

   FWrite(nHandle, mEof, Len(mEof))
   FClose(nHandle)

   RETURN r

Grato pela atenção de todos.

Planilha XML padrão Excel

Enviado: 13 Set 2023 10:06
por JoséQuintas
Aqui abriu no open office mas mostra como se fosse XML numa célula.
excel.png

Planilha XML padrão Excel

Enviado: 13 Set 2023 10:15
por Itamar M. Lins Jr.
Olá!
Renomear para XML.
Captura de tela 2023-09-13 103418.png
Saudações,
Itamar M. Lins Jr.

Planilha XML padrão Excel

Enviado: 13 Set 2023 12:05
por JoséQuintas
Com base nisso indicaria a investigação da empresa.
Só uma empresa manda dinheiro pra prefeitura?
E bastante dinheiro, com nome supostamente de empresa pequena.

Não sei se a informação seria confidencial.

Sobre a planilha, no open-office não foi, pediu instalação de java.

Planilha XML padrão Excel

Enviado: 13 Set 2023 12:56
por clodoaldomonteiro
JoséQuintas escreveu:Com base nisso indicaria a investigação da empresa.
Só uma empresa manda dinheiro pra prefeitura?
E bastante dinheiro, com nome supostamente de empresa pequena.

Não sei se a informação seria confidencial.

Sobre a planilha, no open-office não foi, pediu instalação de java.
Quintas, o documento é como se fosse um extrato bancário, e é público, mas não vamos nos ater a isso.

Na minha demanda, era só pra Excel mesmo, pois não tenho clientes com .odf ou outra estenção.

Abraços.

Planilha XML padrão Excel

Enviado: 13 Set 2023 12:58
por clodoaldomonteiro
Itamar M. Lins Jr. escreveu:Olá!
Renomear para XML.
Captura de tela 2023-09-13 103418.png
Saudações,
Itamar M. Lins Jr.
Itamar, optei por salvar com .xsl, pra que o cliente quando clicar duas vezes no arqui, abra pelo Excel, mas quem for usar, pode mudar a extensão.

Planilha XML padrão Excel

Enviado: 13 Set 2023 14:20
por Itamar M. Lins Jr.
Olá!
Eu e José "confusão" Quintas usamos LibreOffice.
Pq acredito que usamos minimamente. Para não precisar instalar programas piratas e com a pirataria o vírus!

Alias trocando um pouco o assunto, esperando OS dos CHINESES! Os americanos estão falidos! Pelo menos é o que dizem os analistas financeiros.

Saudações,
Itamar M. Lins Jr.

Planilha XML padrão Excel

Enviado: 13 Set 2023 14:50
por clodoaldomonteiro
Bom Itamar, pra ficar bem claro....

Até onde sei, meus clientes (contadores e prefeituras), não usam programas piratas ou algo desse tipo, pois sei que eles compram as licenças do Office de vendedores certificados.

E no meu caso, afirmo que não uso qualquer produto da MS que seja pirateado, nem S.O. e não o pacote Office, pois eu os compro desde 1996.

E também, não critico quem queira usar isso ou aqui, pirata ou não, cada um segue a cartilha que bem entender, sem problemas mesmo.

E por fim, estou somente demonstrando como resolvi um problema que tinha, de não conseguir gerar planilhas "um pouco formatada" para meus clientes.

Fico a disposição para dirimir quaisquer dúvidas sobre o post, sem nenhum problema mesmo.

Abraços.

Planilha XML padrão Excel

Enviado: 13 Set 2023 15:10
por Itamar M. Lins Jr.
Olá!
Isso ai tudo que escreveu, é a sua interpretação de texto. Não posso fazer nada quanto a isso.
Não afirmei nada disso que vc supostamente entendeu e escreveu.

Eu evito instalar no meu micro, quanto aos outros, problema de cada um.

Saudações,
Itamar M. Lins Jr.

Planilha XML padrão Excel

Enviado: 13 Set 2023 16:48
por clodoaldomonteiro
Sem problema, Itamar.
E fico grato pelos avisos e justificativas.

Abraços.

Planilha XML padrão Excel

Enviado: 13 Set 2023 17:22
por JoséQuintas
Itamar M. Lins Jr. escreveu:Eu e José "confusão" Quintas usamos LibreOffice.
Correção: aqui uso OpenOffice portátil
Uma vez cada dois meses, mas uso.

Planilha XML padrão Excel

Enviado: 14 Set 2023 10:23
por clodoaldomonteiro
Bom dia.

Fiz umas atualizações nos fontes, incluindo uma rotina para verificar os CRLF e transformar em espaço em branco, e outras correções de caracteres.
Inclui também verificações e mensagens na hora de Criar, Salvar e Copiar arquivo XML.
Acho que na primeira já tinha Cabeçalho e Rodapé.

Uma coisa interessante seria usar "MSXML2.DOMDocument.6.0" para validar a Syntax do XML gerado. Quem puder ajudar, ficaria grato.

Código: Selecionar todos

////////////////////////////////////////////////////////////////////////////////
/*
Funções para Gerar XML e salvar como .xls pra ler no MS Excel

-Exemplo de aCabecalho{}:
aCabecalho := {;
 {"Data"          , 047},;
 {"DIA C¢digo"    , 047},;
 {"CAP C¢digo"    , 047},;
 {"PCASP Conta"   , 070},;
 {"Hist¢rico"     , 200},;
 {"Documento"     , 100},;
 {"U.O"           , 047},;
 {"Fonte Recurso" , 047},;
 {"Valor D‚bito"  , 070},;
 {"Valor Cr‚dito" , 070},;
 {"Saldo"         , 070};
 }

-Exemplo de registro SaldoInicial em aTabela{}:
AAdd( aTabela, {;   //Linha de Totais
 '01/' + pe_mm,;
 'Saldo inicial',;
 'Conta origem -->',;
 Transform(aDados[i, 4], '@R 99999.99.99'),;
 aDados[i, 5],;
 Trim(cl_ItemArray(aTipoContaBancaria, aDados[i, 21], 2))+;
 ", Banco: " + aDados[i, 1] + ', Agˆncia: ' + aDados[i, 2]  +;
 ', Conta Banc ria: ' + Transform(aDados[i, 3], '@R 999.999.999.999'),;
 '',;          //UO
 '',;          //FR
 '',;          //D‚bito
 '',;          //Cr‚dito
 {'Saldo', aDados[i, 6]}; //Saldo
 })

-Exemplo de registro TotalFinal em aTabela{}:
AAdd( aTabela, {;   //Linha de Totais
 'éltimo dia',;
 '',;
 '',;
 '',;
 'TOTAL DA CONTA BANCµRIA: Qtd - ' + Str(i, 5),;
 '',;
 '',;
 '',;
 {'Total', TDebSLD},;
 {'Total', TCreSLD},;
 {'Total', mSaldo};
 })

-Exemplo de Hash com fórmula para coluna de aTabela{}.
hSaldo := {;
 "Formula" => '=RC[-4]+RC[-3]-RC[-2]',;
 "Number"  => vl_fixatu + mSupAnu - mValor1 }

/*
If emp_codigo = '003237'
   i := At('funcional', Lower( emp_histor) )
   msg := subs(emp_histor, i, 15)
   x:= msg + CRLF
   For i := 1 To Len(msg)
      x += subs(msg, i, 1) + Str(asc(subs(msg, i, 1))) + CRLF
   Next
   ADOStringGrava( x )
Endif
*/

*/
////////////////////////////////////////////////////////////////////////////////

//#pragma -w0
//#pragma -es0

//#include "hbcompat.ch"

#include "Fileio.ch"
#define CRLF  Chr(13)+Chr(10)

MemVar M_VERSAO, userName, nEmp, pathTmp

//////////////////////////////////////////////////////////////////////////////////
//FUNCOES PARA GERAR XLS
Function xmlGeraTabela(cFile, cWorksheetName, aCabecalho, aTabela, cRelName)
   Local msg, nHandle, r := .t., nLenTabela := Len(aTabela) + 5
   Local mArqTemp := pathTmp + 'XMLTemp_' + cl_GetNomeArq() + '.xml'

   If IsDirectory( pathTmp )

      nHandle := FCreate(mArqTemp, FC_NORMAL )  //Cria um arquivo temporário

      If FError() = 0

         xmlOpenBook(nHandle, cWorksheetName, aCabecalho, nLenTabela, cRelName )

         xmlWriteRow(nHandle, aTabela )

         xmlRodape( nHandle, nLenTabela, Len(aCabecalho) -1 )

         xmlCloseBook( nHandle )

         If FClose( nHandle )

            If FileCopy( mArqTemp, cFile ) = 0                            //faz cópia de arquivo temporário para o definitivo

               r := .f.

               msg := 'Não consegui COPIAR arquivo temporário (XML/XLS Excel) da pasta temporária para a pasta XLS da Empresa.'
               msg += CRLF + 'Verifique se a pasta existe e se o arquivo está aberto por outra aplicação.'
               msg += CRLF + 'Arquivo origem: ' + mArqTemp
               msg += CRLF + 'Arquivo destino: ' + cFile

               MsgError( msg )

            EndIf

         Else

            r := .f.

            msg := 'Falha ao SALVAR arquivo temporário XML/XLS Excel na pasta ..\Temp.'
            msg += CRLF + 'Verifique se a pasta existe e se o arquivo está aberto por outra aplicação.'
            msg += CRLF + 'Arquivo: ' + mArqTemp
            msg += CRLF + 'Cõdigo do erro: ' + LTrim(Str( FError() ))

            MsgAtencao( msg )

         Endif

      Else

         r := .f.

         msg := 'Falha ao CRIAR arquivo temporário XML/XLS Excel na pasta ..\Temp.'
         msg += CRLF + 'Verifique se a pasta existe e se o arquivo está aberto por outra aplicação.'
         msg += CRLF + 'Arquivo: ' + mArqTemp
         msg += CRLF + 'Cõdigo do erro: ' + LTrim(Str( FError() ))

         MsgAtencao( msg )

      Endif

   Else

      r := .f.

      msg := 'Falha ao abrir pasta para arquivo temporário XML/XLS Excel na pasta ..\Temp.'
      msg += CRLF + 'Provavelmente a pasta não existe.'
      msg += CRLF + 'Caminho: ' + pathTmp

      MsgAtencao( msg )

   Endif

   Return r

   /////////////////////////////////////////////////////////////////////////////
   //Largura padrão das cell é 47, definido em <Column ss:Index="1" ss:AutoFitWidth="0" ss:Width="47"/>
   //"ExpandedColumnCount" registra a quantidade de colunas da tabela
FUNCTION xmlOpenBook(nHandle, cWorksheetName, aCabecalho, nRowCount, cRelName)
   LOCAL mBof := '', i
   Local nMergeLeft := Int( (Len(aCabecalho) -1) / 2), nMergeRight := (Len(aCabecalho) -1) - nMergeLeft -1

   mBof += [<!--SimplesInformatica.com.br-->] + CRLF

   mBof += [<?xml version="1.0"?>] + CRLF
   mBof += [<?mso-application progid="Excel.Sheet"?>] + CRLF
   mBof += [<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"] + CRLF
   mBof += [ xmlns:o="urn:schemas-microsoft-com:office:office"] + CRLF
   mBof += [ xmlns:x="urn:schemas-microsoft-com:office:excel"] + CRLF
   mBof += [ xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"] + CRLF
   mBof += [ xmlns:html="http://www.w3.org/TR/REC-html40">] + CRLF
   mBof += [ <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">] + CRLF
   mBof += [  <Version>12.00</Version>] + CRLF
   mBof += [ </DocumentProperties>] + CRLF

   mBof += [ <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">] + CRLF
   mBof += [  <WindowHeight>10005</WindowHeight>] + CRLF
   mBof += [  <WindowWidth>10005</WindowWidth>] + CRLF
   mBof += [  <WindowTopX>120</WindowTopX>] + CRLF
   mBof += [  <WindowTopY>135</WindowTopY>] + CRLF
   mBof += [  <ProtectStructure>False</ProtectStructure>] + CRLF
   mBof += [  <ProtectWindows>False</ProtectWindows>] + CRLF
   mBof += [ </ExcelWorkbook>] + CRLF

   mBof += [ <Styles>] + CRLF

   mBof += [  <Style ss:ID="Default" ss:Name="Normal">] + CRLF
   mBof += [   <Alignment ss:Vertical="Bottom"/>] + CRLF
   mBof += [   <Borders/>] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"/>] + CRLF
   mBof += [   <Interior/>] + CRLF
   mBof += [   <NumberFormat/>] + CRLF
   mBof += [   <Protection/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CellCabeca">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#EAF1DD" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="ValorContabil">] + CRLF
   mBof += '   <NumberFormat ss:Format="#,##0.00_ ;[Red]\-#,##0.00\ "/>' + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CellSaldo">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#E5E0EC" ss:Pattern="Solid"/>] + CRLF
   mBof += '   <NumberFormat ss:Format="[Blue]#,##0.00_ ;[Red]\-#,##0.00\ "/>' + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CellTotal">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#D8D8D8" ss:Pattern="Solid"/>] + CRLF
   mBof += '   <NumberFormat ss:Format="[Blue]#,##0.00_ ;[Red]\-#,##0.00\ "/>' + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CellRodapeLeft">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   //mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="9" ss:Color="#4F6228" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#D8D8D8" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="s74" ss:Name="Hyperlink">] + CRLF
   mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#0000FF" ss:Underline="Single"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CellRodapeRight" ss:Parent="s74">] + CRLF
   mBof += [   <Alignment ss:Horizontal="Right" ss:Vertical="Bottom"/>] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   //mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   //mBof += [   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#4F6228" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#D8D8D8" ss:Pattern="Solid"/>] + CRLF
   mBof += [   <Protection/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CabecalhoLeftTop">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Times New Roman" x:Family="Roman" ss:Size="14" ss:Color="#000000" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#DBEEF3" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CabecalhoLeftBottom">] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Font ss:FontName="Times New Roman" x:Family="Roman" ss:Size="13" ss:Color="#000000" ss:Bold="1"/>] + CRLF
   mBof += [   <Interior ss:Color="#DBEEF3" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CabecalhoRightTop">] + CRLF
   mBof += [   <Alignment ss:Horizontal="Right" ss:Vertical="Bottom"/>] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Interior ss:Color="#DBEEF3" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [  <Style ss:ID="CabecalhoRightBottom">] + CRLF
   mBof += [   <Alignment ss:Horizontal="Right" ss:Vertical="Bottom"/>] + CRLF
   mBof += [   <Borders>] + CRLF
   mBof += [    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>] + CRLF
   mBof += [   </Borders>] + CRLF
   mBof += [   <Interior ss:Color="#DBEEF3" ss:Pattern="Solid"/>] + CRLF
   mBof += [  </Style>] + CRLF

   mBof += [ </Styles>] + CRLF

   mBof += [ <Worksheet ss:Name="] + hb_strToUTF8(cWorksheetName) + [">] + CRLF

   mBof += [  <Table ss:ExpandedColumnCount="] + LTrim(Str(Len(aCabecalho))) + [" ss:ExpandedRowCount="] + LTrim(Str(nRowCount)) + [" x:FullColumns="1" x:FullRows="1" ss:DefaultRowHeight="15">] + CRLF

   For i := 1 To Len(aCabecalho)
      mBof += [   <Column ss:Index="] + LTrim(Str(i)) + [" ss:AutoFitWidth="0" ss:Width="] + LTrim(Str(aCabecalho[i, 2])) + ["/>] + CRLF
   Next

   mBof += [   <Row ss:AutoFitHeight="0" ss:Height="19">] + CRLF
   mBof += [    <Cell ss:MergeAcross="] + LTrim(Str(nMergeLeft)) +;
   [" ss:StyleID="CabecalhoLeftTop"><Data ss:Type="String">] + xmlAjustaString( nEmp ) + [</Data></Cell>] + CRLF
   mBof += [    <Cell ss:MergeAcross="] + LTrim(Str(nMergeRight)) +;
   [" ss:StyleID="CabecalhoRightTop"><Data ss:Type="String">Top</Data></Cell>] + CRLF
   mBof += [   </Row>] + CRLF

   mBof += [   <Row ss:AutoFitHeight="0" ss:Height="19">] + CRLF
   mBof += [    <Cell ss:MergeAcross="] + LTrim(Str(nMergeLeft)) +;
   [" ss:StyleID="CabecalhoLeftBottom"><Data ss:Type="String">] + xmlAjustaString( cRelName ) + [</Data></Cell>] + CRLF
   mBof += [    <Cell ss:MergeAcross="] + LTrim(Str(nMergeRight)) +;
   [" ss:StyleID="CabecalhoRightBottom"><Data ss:Type="String">Valores em (R$)</Data></Cell>] + CRLF
   mBof += [   </Row>] + CRLF

   mBof += [   <Row ss:AutoFitHeight="0">] + CRLF
   For i := 1 To Len(aCabecalho)
      mBof += [    <Cell ss:Index="] + LTrim(Str(i)) + [" ss:StyleID="CellCabeca"><Data ss:Type="String">] + hb_strToUTF8( aCabecalho[i, 1] ) + [</Data></Cell>] + CRLF
   Next
   mBof += [   </Row>] + CRLF

   FWrite(nHandle, mBof, Len(mBof))

   RETURN nil

   /////////////////////////////////////////////////////////////////////////////
   //Para Cell com Formula, usa-se ss:Formula.
   // - Ex.: col D [= A + B - C]. Levanta-se a array RC[x], onde seria o valor da posição de D - a posição da col a ser usada.
   // - Explicando RC[] (R = Row e C = Col)
   // - Ficando: < ... ss:Formula="=RC[-4]+RC[-3]-RC[-2]"><Data ...
FUNCTION xmlWriteRow(nHandle, aTabela )
   LOCAL mRow, i, x

   For i := 1 TO Len(aTabela)
      mRow := [   <Row ss:AutoFitHeight="0">] + CRLF

      For x := 1 To Len(aTabela[i])

         If Valtype(aTabela[i, x]) = 'N'
            mRow += [    <Cell ss:StyleID="ValorContabil"><Data ss:Type="Number">] + LTrim(Str(aTabela[i, x], 11,2)) + [</Data></Cell>] + CRLF

         ElseIf Valtype(aTabela[i, x]) = 'A'
            If aTabela[i, x, 1] = 'Saldo'
               mRow += [    <Cell ss:StyleID="CellSaldo"><Data ss:Type="Number">] + LTrim(Str(aTabela[i, x, 2], 11,2)) + [</Data></Cell>] + CRLF

            ElseIf aTabela[i, x, 1] = 'Total'
               mRow += [    <Cell ss:StyleID="CellTotal"><Data ss:Type="Number">] + LTrim(Str(aTabela[i, x, 2], 11,2)) + [</Data></Cell>] + CRLF

            Else
               mRow += [    <Cell ss:StyleID="ValorContabil"><Data ss:Type="Number">] + LTrim(Str(aTabela[i, x], 11,2)) + [</Data></Cell>] + CRLF

            Endif

         ElseIf Valtype(aTabela[i, x]) = 'H'
            mRow += [    <Cell ss:StyleID="ValorContabil" ss:Formula="] + aTabela[i, x]["Formula"] +["><Data ss:Type="Number">] + LTrim(Str(aTabela[i, x]["Number"], 11,2)) + [</Data></Cell>] + CRLF

         Else
            mRow += [    <Cell><Data ss:Type="String" x:Ticked="1">] + xmlAjustaString( aTabela[i, x] ) + [</Data></Cell>] + CRLF

         Endif
      Next

      mRow += [   </Row>] + CRLF

      FWrite(nHandle, mRow, Len(mRow))

   Next nI

   RETURN nil


Function xmlRodape(nHandle, nLenTabela, nLenCabecalho)
   LOCAL mRow, nMergeLeft := Int( nLenCabecalho / 2), nMergeRight := nLenCabecalho - nMergeLeft -1

   mRow := [   <Row ss:Index="] + LTrim(Str(nLenTabela)) + [" ss:AutoFitHeight="0">] + CRLF

   mRow += '    <Cell ss:MergeAcross="' + LTrim(Str(nMergeLeft)) + '" ss:StyleID="CellRodapeLeft">' +;
    '<Data ss:Type="String">'+ hb_strToUTF8('Usu rio: ' + AlLTrim(userName) ) +;
    ' | Data: ' + TtoC(DateTime()) + ' | SIAFIC: SCP21H / Ver: ' + M_VERSAO +;
    ' / File: ' + ProcFile(2) + '</Data></Cell>' + CRLF

   mRow += '    <Cell ss:MergeAcross="' + LTrim(Str(nMergeRight)) +;
    '" ss:StyleID="CellRodapeRight" ss:HRef="https://www.simplesinformatica.com.br/">' +;
    '<Data ss:Type="String">www.SimplesInformatica.com.br</Data></Cell>' + CRLF

   mRow += [   </Row>] + CRLF

   FWrite(nHandle, mRow, Len(mRow))

   Return nMergeRight


   /////////////////////////////////////////////////////////////////////////////
   //Fecha e grava o arquivo.
   //Retorna True se tudo der certo e False caso tenha acontecido algum erro ao gravar.
   //FError() pode ser usado para conferir o erro
FUNCTION xmlCloseBook( nHandle )
   LOCAL mEof := ''

   mEof += [  </Table>] + CRLF

   mEof += [  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">] + CRLF

   mEof += [   <PageSetup>] + CRLF
   mEof += [    <Header x:Margin="0.4921259845"/>] + CRLF
   mEof += [    <Footer x:Margin="0.4921259845"/>] + CRLF
   mEof += [    <PageMargins x:Bottom="0.984251969" x:Left="0.78740157499999996" x:Right="0.78740157499999996" x:Top="0.984251969"/>] + CRLF
   mEof += [   </PageSetup>] + CRLF

   mEof += [   <Unsynced/>] + CRLF

   mEof += [   <Print>] + CRLF
   mEof += [    <ValidPrinterInfo/>] + CRLF
   mEof += [    <PaperSizeIndex>9</PaperSizeIndex>] + CRLF
   mEof += [    <HorizontalResolution>600</HorizontalResolution>] + CRLF
   mEof += [    <VerticalResolution>600</VerticalResolution>] + CRLF
   mEof += [   </Print>] + CRLF

   mEof += [   <Selected/>] + CRLF

   mEof += [   <FreezePanes/>] + CRLF     //Congela a primeira linha
   mEof += [   <FrozenNoSplit/>] + CRLF
   mEof += [   <SplitHorizontal>3</SplitHorizontal>] + CRLF
   mEof += [   <TopRowBottomPane>3</TopRowBottomPane>] + CRLF
   mEof += [   <ActivePane>2</ActivePane>] + CRLF

   mEof += [   <Panes>] + CRLF
   mEof += [    <Pane>] + CRLF
   mEof += [     <Number>3</Number>] + CRLF
   mEof += [    </Pane>] + CRLF
   mEof += [    <Pane>] + CRLF
   mEof += [     <Number>2</Number>] + CRLF
   mEof += [     <ActiveCol>1</ActiveCol>] + CRLF
   mEof += [    </Pane>] + CRLF
   mEof += [   </Panes>] + CRLF

   mEof += [   <ProtectObjects>False</ProtectObjects>] + CRLF
   mEof += [   <ProtectScenarios>False</ProtectScenarios>] + CRLF

   mEof += [  </WorksheetOptions>] + CRLF

   mEof += [ </Worksheet>] + CRLF

   mEof += [</Workbook>]

   FWrite(nHandle, mEof, Len(mEof))

   RETURN nil


   /////////////////////////////////////////////////////////////////////
   //Substitui os caracteres especiais do XML
   //http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
   //https://www.freeformatter.com/xml-escape.html#before-output
Function cl_XmlCarac( cString )

   cString := AlLTrim( cString )
   cString := StrTran( cString, '&', '&')
   cString := StrTran( cString, '<', '<')
   cString := StrTran( cString, '>', '>')
   cString := StrTran( cString, "'", '&apos;')
   cString := StrTran( cString, '"', '"')

   cString := StrTran( cString, Chr(141) + CRLF, ' ')
   cString := StrTran( cString, Chr(141) + Chr(10), ' ')
   cString := StrTran( cString, Chr(141), ' ')
   cString := StrTran( cString, '', ' ')

   cString := StrTran( cString, Chr(222), '') //Þ
   //cString := StrTran( cString, '', ' ')

   cString := StrTran( cString, Chr(204) + CRLF, '') // Ì
   cString := StrTran( cString, 'ì', ' ')

   cString := StrTran( cString, CRLF, '. ')
   cString := StrTran( cString, Chr(10), '')
   cString := StrTran( cString, Chr(13), '')

   If Right(cString, 1) = '-'
      cString := Left( cString, Len(cString)-1)
   EndIf

   /*
   cString := StrTran( cString, 'º', 'º')
   cString := StrTran( cString, '°', '&ring;')
   cString := StrTran( cString, 'ª', 'ª')
   cString := StrTran( cString, '..', '.')
   cString := StrTran( cString, '-', '.')
   */

   Return cString

Function xmlAjustaString( cString )

   cString := AllTrim( cString )
   cString := cl_XmlCarac( cString )
   cString := hb_strToUTF8( cString )

   Return cString

Abraços.

Planilha XML padrão Excel

Enviado: 14 Set 2023 10:44
por JoséQuintas
https://github.com/JoseQuintas/sefazcla ... zclass.prg

DomDocValidaXml()
ou
SefazclassValidaXml()
ou
Sefazclass():ValidaXml()

Planilha XML padrão Excel

Enviado: 14 Set 2023 12:12
por JoséQuintas
anp.png
Parece piada mas....
Eu só uso OpenOffice pra abrir essas planilhas mensais da ANP XLS, e salvar em formato Excel - sei lá porque não dá pra abrir direto.

Tem tabela interessante inclusive:

- tabela de países com código (usa na NFE)
- tabela de UFs com código (usa na NFE)
- tabela de cidades com código (usa na NFE)
- tabelas de produtos ANP (usa na NFE)
- tabela de empresas abertas e fechadas (essa só usa pra ANP mesmo)
- tabela de instalações abertas e fechadas (essa só usa pra ANP mesmo) é parecida com a anterior, sei lá porque são duas

Planilha XML padrão Excel

Enviado: 14 Set 2023 12:30
por Ana Mitoooo
Em se falando de manipulação de arquivos XML (Texto) o Harbour disponibiliza a Biblioteca mxml
É muita POG manipular o XML como fosse texto simples (funciona, mas vai ter trabalho multiplicado e erros de formato a rodo)

Código: Selecionar todos

#include "hbmxml.ch"
#xcommand Xml_Base INTO <v> => #pragma __text|<v>+=%s;<v>:=""

Static xml_Error___ := ''
Static xml_Status__ := .F.

/* ----------------------------------- */
/* Cria Planilha em XML
/* ----------------------------------- */
Proc sh_Create()

   Local i, n
   Local oXML
   Local hXML := hb_Hash()

   hXML[ "Cols" ] := 16
   hXML[ "Rows" ] := 10

   // Log erros XML
   mxmlSetErrorCallback( @sh_XmlError() )

   // Sem quebra de linha
   mxmlSetWrapMargin( 0 )

   // Manipulação XML
   oXml := mxmlLoadString( NIL, sh_XmlBase(), MXML_OPAQUE_CALLBACK )

   // Verifica XML
   If xml_Status__
      hb_Alert( 'ERRO: ' + xml_Error___ )
   End

   // Localiza TAG/Node
   hXML[ "Table" ] := mxmlFindElement( oXml, oXml, "Table", NIL, NIL, MXML_DESCEND )
   If Empty( hXML[ "Table" ] )
      F_Msg_Info( 'Erro: Tag ' + "Table", __AC_SYSDATA[ Act_sApl_Running__ ] )
   Else

      // Formata Colunas
      For i := 1 To hXML[ "Cols" ]
         hXML[ 'Column' ] := mxmlNewElement( hXML[ "Table" ], 'Column' )
         mxmlElementSetAttr( hXML[ "Column" ], 'ss:Index', hb_NTos( i ) )
         mxmlElementSetAttr( hXML[ "Column" ], 'ss:AutoFitWidth', '0' )
         mxmlElementSetAttr( hXML[ "Column" ], 'ss:Width', '64' )
      Next

      // Linha Cabeçalho
      hXML[ 'Row' ] := mxmlNewElement( hXML[ "Table" ], 'Row' )
      mxmlElementSetAttr( hXML[ "Row" ], 'ss:AutoFitHeight', '0' )
      For i := 1 To hXML[ "Cols" ]
         hXML[ 'Cell' ] := mxmlNewElement( hXML[ "Row" ], 'Cell' )
         mxmlElementSetAttr( hXML[ "Cell" ], 'ss:StyleID', 's62' )
         hXML[ 'Data' ] := mxmlNewElement( hXML[ "Cell" ], 'Data' )
         mxmlElementSetAttr( hXML[ "Data" ], 'ss:Type', 'String' )
         mxmlNewText( hXML[ 'Data' ], 0, StrZero( i, 9 ) )
      Next

      // Dados Tabela
      For i := 1 To hXML[ "Rows" ]

         hXML[ 'Row' ] := mxmlNewElement( hXML[ "Table" ], 'Row' )
         mxmlElementSetAttr( hXML[ "Row" ], 'ss:AutoFitHeight', '0' )

         For n := 1 To hXML[ "Cols" ]
           hAux[ 'Cell' ] := mxmlNewElement( hAux[ "Row" ], 'Cell' )
           hAux[ 'Data' ] := mxmlNewElement( hAux[ "Cell" ], 'Data' )
           mxmlElementSetAttr( hAux[ "Data" ], 'ss:Type', 'String' )
           mxmlNewText( hAux[ 'Data' ], 0, StrZero( i, 9 ) )
         Next

      Next

      // Ajusta dados da planilha (Linhas e Colunas)
      mxmlElementSetAttr( hAux[ "Table" ], 'ss:ExpandedColumnCount', hb_NToS( hXML[ "Cols" ] ) )
      mxmlElementSetAttr( hAux[ "Table" ], 'ss:ExpandedRowCount', hb_NToS( hXML[ "Rows" ] + 1 ) )

   Endif

   mxmlSaveFile( oXml, 'c:\temp\planilha.xls' )
   mxmlDelete( oXml )

Return cXml

/* ----------------------------------- */
/* XML Base para Planilha em XML
/* ----------------------------------- */
Func sh_XmlBase()

Local cXml

Xml_Base into cXml
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">
 <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
  <Author>Ana Mitoooo</Author>
  <Version>12.00</Version>
 </DocumentProperties>
 <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
  <WindowHeight>12600</WindowHeight>
  <WindowWidth>28755</WindowWidth>
  <WindowTopX>0</WindowTopX>
  <WindowTopY>75</WindowTopY>
  <ProtectStructure>False</ProtectStructure>
  <ProtectWindows>False</ProtectWindows>
 </ExcelWorkbook>
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"/>
   <Borders/>
   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
  <Style ss:ID="s62">
   <Alignment ss:Horizontal="Center" ss:Vertical="Bottom"/>
   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"
    ss:Bold="1"/>
  </Style>
  <Style ss:ID="s63">
   <Alignment ss:Horizontal="Center" ss:Vertical="Bottom"/>
   <NumberFormat ss:Format="Short Date"/>
  </Style>
  <Style ss:ID="s64">
   <NumberFormat ss:Format="Standard"/>
  </Style>
 </Styles>
 <Worksheet ss:Name="XML SpreadSheet">
  <Table ss:ExpandedColumnCount="0" ss:ExpandedRowCount="0" x:FullColumns="1" x:FullRows="1" ss:DefaultRowHeight="15">
  </Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <PageSetup>
    <Header x:Margin="0.31496062000000002"/>
    <Footer x:Margin="0.31496062000000002"/>
    <PageMargins x:Bottom="0.78740157499999996" x:Left="0.511811024" x:Right="0.511811024" x:Top="0.78740157499999996"/>
   </PageSetup>
   <Unsynced/>
   <Print>
    <ValidPrinterInfo/>
    <PaperSizeIndex>9</PaperSizeIndex>
    <HorizontalResolution>360</HorizontalResolution>
    <VerticalResolution>360</VerticalResolution>
   </Print>
   <Selected/>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
</Workbook>
EndText

cXml := StrTran( cXml, hb_Eol(), '' )
cXml := StrTran( cXml,  ' </', '</' )
cXml := StrTran( cXml,  '/> ', '/>' )

Return cXml

/* ----------------------------------- */
/* Log erros XML
/* ----------------------------------- */
Static Proc sh_XmlError( s_Erro )

   xml_Error___ += s_Erro + hb_Eol()
   xml_Status__ := .T.

RETURN
*Código não testado, exemplo para manipular XML

https://www.msweet.org/mxml/mxml.html#introduction