Wednesday 26 July 2017

Centered Moving Average Xls


Maio de 2015 Estimativas nacionais de emprego e salário ocupacional Estados Unidos Estas estimativas são calculadas com dados coletados de empregadores em todos os setores da indústria em áreas metropolitanas e não-metropolitanas em todos os estados eo Distrito de Columbia. Informações adicionais, incluindo os salários de percentil 10, 25, 75 e 90 e os percentuais de porcentagem relativa, estão disponíveis no arquivo XLS para download. Principais Grupos Ocupacionais (Nota --clicando um link irá rolar a página para o grupo ocupacional): Para classificar esta tabela por uma coluna diferente, clique no cabeçalho da coluna Título da ocupação (clique no título da ocupação para ver seu perfil) (1) As estimativas para ocupações detalhadas não somam os totais porque os totais incluem ocupações não mostradas separadamente. As estimativas não incluem trabalhadores independentes. (2) Os salários anuais foram calculados multiplicando-se o salário médio por hora por um número de horas-quotyear-round, full-timequot hours de 2.080 horas para aquelas ocupações onde não há um salário por hora publicado, o salário anual foi calculado diretamente do relatório dados de pesquisa. (3) O erro padrão relativo (RSE) é uma medida da confiabilidade de uma estatística de levantamento. Quanto menor o erro padrão relativo, mais precisa a estimativa. (4) Salários para algumas ocupações que geralmente não trabalham o ano todo, a tempo inteiro, são relatados como salários por hora ou salários anuais, dependendo de como eles são normalmente pagos. (5) Este salário é igual ou superior a 90,00 por hora ou 187.200 por ano. Todos os anos os nossos alunos registram mais de 4.500 horas de voluntariado em escolas locais, clínicas e outros locais da comunidade. Eles ganham uma visão em primeira mão em cuidados primários e experimentam a diferença que podem fazer para indivíduos e comunidades inteiras. Servindo vizinhos em necessidade Profissional com prestadores de cuidados de saúde bem treinados, a recentemente ampliada Clínica da Comunidade Heritage está aberta para residentes do sul do Ohio que precisam de cuidados mais. A clínica oferece gratuitamente exames de saúde de baixo custo, imunizações, exames, tratamento de diabetes e outros cuidados especializados. Para escrever uma string, uma string formatada, um número e uma fórmula para a primeira planilha em um livro do Excel chamado perl. xlsx: The O módulo Excel :: Writer :: XLSX pode ser usado para criar um arquivo Excel no formato XLSX 2007. O formato XLSX é o formato Office Open XML (OOXML) usado pelo Excel 2007 e posterior. Várias planilhas podem ser adicionadas a uma pasta de trabalho ea formatação pode ser aplicada às células. Texto, números e fórmulas podem ser escritos para as células. Este módulo ainda não pode ser usado para gravar em um arquivo Excel XLSX existente. Excel :: Writer :: XLSX usa a mesma interface que o módulo Spreadsheet :: WriteExcel que produz um arquivo do Excel no formato XLS binário. Excel :: Writer :: XLSX suporta todos os recursos do Spreadsheet :: WriteExcel e em alguns casos tem mais funcionalidade. Para obter mais detalhes, consulte 34Compatibilidade com Spreadsheet :: WriteExcel34. A principal vantagem do formato XLSX sobre o formato XLS é que permite um maior número de linhas e colunas em uma planilha. O formato de arquivo XLSX também produz arquivos muito menores do que o formato de arquivo XLS. Excel :: Writer :: XLSX tenta fornecer uma interface para o maior número de recursos do Excel39s possível. Como resultado, há uma grande quantidade de documentação para acompanhar a interface e pode ser difícil à primeira vista ver o que é importante eo que não é. Então, para aqueles de vocês que preferem montar móveis Ikea primeiro e depois ler as instruções, aqui estão três passos fáceis: 1. Criar um novo livro do Excel (ou seja, arquivo) usando new (). 2. Adicionar uma folha de cálculo ao novo livro utilizando addworksheet (). 3. Escreva para a folha de cálculo utilizando write (). Isso criará um arquivo Excel chamado perl. xlsx com uma única planilha eo texto 39Hi Excel39 na célula relevante. E isso é tudo. Ok, então não é realmente um passo zeroth, bem, mas usar o módulo vai sem dizer. Há muitos exemplos que vêm com a distribuição e que você pode usar para você começar. Consulte 34EXAMPLES34. Aqueles de vocês que lerem as instruções primeiro e montarem os móveis depois saberão como proceder. -) O módulo Excel :: Writer :: XLSX fornece uma interface orientada a objeto para uma nova pasta de trabalho do Excel. Os métodos a seguir estão disponíveis por meio de um novo pasta de trabalho. Se você não estiver familiarizado com interfaces orientadas a objeto ou a maneira que eles são implementados em Perl ter um olhar para perlobj e perltoot na documentação Perl principal. Um novo livro do Excel é criado usando o construtor new () que aceita um nome de arquivo ou um filehandle como um parâmetro. O exemplo a seguir cria um novo arquivo do Excel baseado em um nome de arquivo: Aqui estão alguns outros exemplos de usar new () com nomes de arquivos: Os dois últimos exemplos demonstram como criar um arquivo no DOS ou Windows onde é necessário escapar do separador de diretório Ou para usar aspas simples para garantir que ele não é interpolado. Para obter mais informações, consulte perlfaq5: Por que can39t eu uso 34C: tempfoo34 em caminhos DOS. Recomenda-se que o nome do arquivo utilize a extensão. xlsx em vez de. xls, uma vez que o último causa um aviso do Excel quando usado com o formato XLSX. O construtor new () retorna um objeto Excel :: Writer :: XLSX que você pode usar para adicionar planilhas e armazenar dados. Deve-se notar que, embora o meu não seja especificamente exigido, ele define o escopo da nova variável de pasta de trabalho e, na maioria dos casos, garante que o caderno de trabalho é fechado adequadamente sem chamar explicitamente o método close (). Se o arquivo não puder ser criado, devido a permissões de arquivo ou algum outro motivo, novo retornará undef. Portanto, é uma boa prática para verificar o valor de retorno do novo antes de prosseguir. Como de costume a variável Perl será definida se houver um erro de criação de arquivo. Você também verá uma das mensagens de aviso detalhadas em 34DIAGNOSTICS34: Você também pode passar um handle de arquivo válido para o novo () construtor. Por exemplo, em um programa CGI você poderia fazer algo como isto: O requisito para binmode () é explicado abaixo. Veja também, o programa cgi. pl no diretório de exemplos da distro. Em programas modperl onde você terá que fazer algo como o seguinte: Veja também, os programas modperl1.pl e modperl2.pl no diretório de exemplos da distro. Filehandles também pode ser útil se você quiser transmitir um arquivo do Excel em um soquete ou se você quiser armazenar um arquivo do Excel em um escalar. Por exemplo, aqui está uma maneira de escrever um arquivo do Excel para um escalar: Consulte também os programas writetoscalar. pl e filehandle. pl no diretório de exemplos da distro. Observe sobre o requisito para binmode (). Um arquivo do Excel é composto de dados binários. Portanto, se você estiver usando um filehandle você deve garantir que você binmode () antes de passá-lo para new (). Você deve fazer isso independentemente de você estar em uma plataforma Windows ou não. Você não precisa se preocupar com binmode () se você estiver usando nomes de arquivos em vez de filehandles. Excel :: Writer :: XLSX executa o binmode () internamente quando converte o nome de arquivo para um filehandle. Para obter mais informações sobre binmode (), consulte perlfunc e perlopentut na documentação principal do Perl. Pelo menos uma planilha deve ser adicionada a uma nova pasta de trabalho. Uma planilha é usada para gravar dados em células: Se sheetname não for especificado, a convenção padrão do Excel será seguida, ie Sheet1, Sheet2, etc. O nome da planilha deve ser um nome de planilha do Excel válido, ou seja, não pode conter nenhum dos seguintes caracteres ,. . E deve ter menos de 32 caracteres. Além disso, você não pode usar o mesmo nomenclatura, sem distinção de maiúsculas e minúsculas, para mais de uma planilha. O método addformat () pode ser usado para criar novos objetos Format que são usados ​​para aplicar formatação a uma célula. Você pode definir as propriedades no momento da criação através de um hash de valores de propriedade ou mais tarde por meio de chamadas de método. Consulte a seção 34CELL FORMATTING34 para obter mais detalhes sobre as propriedades de formatação e como configurá-las. Esse método é usado para criar um novo gráfico como uma planilha autônoma (o padrão) ou como um objeto incorporável que pode ser inserido em uma planilha por meio do método de planilha insertchart (). As propriedades que podem ser definidas são: Este é um parâmetro necessário. Ele define o tipo de gráfico que será criado. Os tipos disponíveis são: Usado para definir um subtipo de gráfico quando disponível. Consulte a documentação Excel :: Writer :: XLSX :: Chart para obter uma lista de subtipos de gráfico disponíveis. Defina o nome da folha de gráfico. A propriedade de nome é opcional e se não for fornecida, o padrão será Chart1. N. O nome deve ser um nome de planilha do Excel válido. Consulte addworksheet () para obter mais detalhes sobre nomes válidos de planilha. A propriedade de nome pode ser omitida para gráficos incorporados. Especifica que o objeto Chart será inserido em uma planilha por meio do método insertchart () Worksheet. É um erro tentar inserir um gráfico que não tenha esse sinalizador definido. Consulte Excel :: Writer :: XLSX :: Chart para obter detalhes sobre como configurar o objeto de gráfico uma vez que ele é criado. Consulte também os programas chart. pl no diretório de exemplos da distribuição. O método addshape () pode ser usado para criar novas formas que podem ser inseridas em uma planilha. Você pode definir as propriedades no momento da criação através de um hash de valores de propriedade ou mais tarde por meio de chamadas de método. Consulte Excel :: Writer :: XLSX :: Shape para obter detalhes sobre como configurar o objeto de forma uma vez que ele é criado. Veja também os programas shape. pl no diretório examples da distro. O método addvbaproject () pode ser usado para adicionar macros ou funções a um arquivo Excel :: Writer :: XLSX usando um arquivo de projeto VBA binário que foi extraído de um arquivo xlsm existente do Excel. O utilitário extractvba fornecido pode ser usado para extrair o arquivo vbaProject. bin requerido de um arquivo existente do Excel: As macros podem ser ligadas a botões usando o método insertbutton () da folha de trabalho (veja a seção 34WORKSHEET METHODS34 para detalhes): Note, Excel usa o arquivo Extensão xlsm em vez de xlsx para arquivos que contêm macros. É aconselhável seguir a mesma convenção. O método setvbaname () pode ser usado para definir o codinome VBA para o pasta de trabalho. Isso às vezes é necessário quando uma macro vbaProject incluída via addvbaproject () se refere à pasta de trabalho. O nome de Excel VBA padrão de ThisWorkbook é usado se um nome definido pelo usuário isn39t especificado. Veja também 34 TRABALHO COM VBA MACROS34. Em geral, o arquivo do Excel será fechado automaticamente quando o programa terminar ou quando o objeto da pasta de trabalho ficar fora do escopo, entretanto, o método close () pode ser usado para fechar explicitamente um arquivo do Excel. Um close () explícito é necessário se o arquivo deve ser fechado antes de executar alguma ação externa sobre ele, como copiá-lo, ler seu tamanho ou anexá-lo a um e-mail. Além disso, close () pode ser necessário para evitar que o coletor de lixo do perl39simule os objetos Workbook, Worksheet e Format na ordem errada. Situações onde isso pode ocorrer são: Se meu () não foi usado para declarar o escopo de uma variável de pasta de trabalho criada usando new (). Se o novo (). Os métodos addworksheet () ou addformat () são chamados em sub-rotinas. A razão para isso é que o Excel :: Writer :: XLSX depende do mecanismo DESTROY do Perl para disparar métodos destrutores em uma seqüência específica. Isso pode não acontecer nos casos em que as variáveis ​​de pasta de trabalho, planilha e formato não são lexicalmente escopo ou onde eles têm diferentes escopos lexical. Em geral, se você criar um arquivo com um tamanho de 0 bytes ou deixar de criar um arquivo, você precisa chamar close (). O valor de retorno de close () é o mesmo que retornado por perl quando fecha o arquivo criado por new (). Isso permite que você lidar com condições de erro da maneira usual: O método setsize () pode ser usado para definir o tamanho de uma janela de pasta de trabalho. O tamanho da janela do Excel foi usado no Excel 2007 para definir a largura ea altura de uma janela de pasta de trabalho dentro da interface de vários documentos (MDI). Em versões posteriores do Excel para Windows essa interface foi descartada. Este método é currectly útil apenas quando definir o tamanho da janela no Excel para Mac 2011. As unidades são pixels eo tamanho padrão é 1073 x 644. Observe, isso doesn39t igualar exatamente para o tamanho do pixel do Excel para Mac, pois é baseado no original Excel 2007 para dimensionamento do Windows. O método setproperties pode ser usado para definir as propriedades do documento do arquivo Excel criado pelo Excel :: Writer :: XLSX. Essas propriedades são visíveis quando você usa a opção Propriedades do Office Button -62 Prepare -62 no Excel e também estão disponíveis para aplicativos externos que lêem ou indexam arquivos do Windows. As propriedades devem ser passadas no formato hash da seguinte maneira: As propriedades que podem ser definidas são: Veja também o programa properties. pl no diretório examples da distro. O método setcustomproperty pode ser usado para definir uma das propriedades de documento personalizadas mais não cobertas pelo método setproperties () acima. Essas propriedades são visíveis quando você usa o botão Office -62 Preparar -62 Propriedades -62 Propriedades avançadas -62 Custom opção no Excel e também estão disponíveis para aplicativos externos que ler ou indexar arquivos do Windows. O método setcustomproperty tem 3 parâmetros: Onde os tipos disponíveis são: As datas devem ser pelo formato de data ISO8601 aaaa-mm-ddThh: mm: ss. sssZ no tempo Zulu, como mostrado acima. Os tipos de texto e número são opcionais, pois geralmente podem ser inferidos a partir dos dados: Os parâmetros de nome e valor são limitados a 255 caracteres por Excel. Esse método é usado para definir um nome que pode ser usado para representar um valor, uma única célula ou um intervalo de células em um pasta de trabalho. Por exemplo, para definir um nome globalworkbook: Também é possível definir um nome de planilha local, prefixando o nome com o nome da planilha usando a sintaxe sheetnamedefinedname: Se o nome da planilha contém espaços ou caracteres especiais, você deve colocá-lo entre aspas simples, como no Excel: Veja o programa definedname. pl no diretório de exemplos da distro. Excel :: Writer :: XLSX armazena dados de planilha em arquivos temporários antes de montar a pasta de trabalho final. O arquivo :: Temp módulo é usado para criar esses arquivos temporários. Arquivo :: Temp usa File :: Spec para determinar um local apropriado para esses arquivos, como tmp ou c: windowstemp. Você pode descobrir qual diretório é usado em seu sistema da seguinte maneira: Se o diretório de arquivo temporário padrão não está acessível ao seu aplicativo, ou não contém espaço suficiente, você pode especificar um local alternativo usando o método settempdir (): O diretório para o temporário Arquivo deve existir, settempdir () não criará um novo diretório. O método é mantido para compatibilidade com Spreadsheet :: WriteExcel. Excel :: Writer :: XLSX programas don39t exigem este método e as cores podem ser especificadas usando um estilo Html RRGGBB valor, consulte 34WORKING COM COLOURS34. O método sheets () retorna uma lista, ou uma lista cortada, das planilhas em uma pasta de trabalho. Se nenhum argumento for passado o método retorna uma lista de todas as planilhas na pasta de trabalho. Isso é útil se você deseja repetir uma operação em cada planilha: Você também pode especificar uma lista de fatias para retornar um ou mais objetos de planilha: Ou, uma vez que o valor de retorno de sheets () é uma referência a um objeto de planilha, você pode escrever o acima Exemplo como: O exemplo a seguir retorna a primeira e última planilha em uma pasta de trabalho: As fatias de matriz são explicadas na página de manual perldata. A função getworksheetbyname () retorna um objeto planilha ou planilha na pasta de trabalho usando o nome da planilha: O Excel armazena as datas como números reais onde a parte inteira armazena o número de dias desde que a época ea parte fracionária armazenam a porcentagem do dia. A época pode ser 1900 ou 1904. Excel para Windows usa 1900 e Excel para Macintosh usa 1904. No entanto, Excel em qualquer plataforma converterá automaticamente entre um sistema e outro. Excel :: Writer :: XLSX armazena datas no formato 1900 por padrão. Se você deseja alterar isso, você pode chamar o método de pasta de trabalho set1904 (). Você pode consultar o valor atual chamando o método de pasta de trabalho get1904 (). Isso retorna 0 para 1900 e 1 para 1904. Consulte também 34DATES AND TIME IN EXCEL34 para obter mais informações sobre como trabalhar com o sistema de data do Excel39s. Em geral, você provavelmente não precisará usar set1904 (). O método setoptimization () é usado para ativar otimizações no módulo Excel :: Writer :: XLSX. Atualmente, há apenas uma otimização disponível e que é reduzir o uso de memória. Observe que, com essa otimização ativada, uma linha de dados é gravada e, em seguida, descartada quando uma célula em uma nova linha é adicionada através de um dos métodos Write () da planilha. Como tais dados devem ser escritos em ordem de linha seqüencial, uma vez que a otimização é ativada. Esse método deve ser chamado antes de quaisquer chamadas para addworksheet (). Defina o modo de cálculo para fórmulas na pasta de trabalho. Isto é principalmente de uso para pastas de trabalho com fórmulas lentas onde você deseja permitir que o usuário para calculá-los manualmente. O parâmetro mode pode ser um dos seguintes strings: O padrão. Excel irá recalcular fórmulas quando uma fórmula ou um valor que afecta a fórmula muda. Somente re-calcular fórmulas quando o usuário exige. Geralmente pressionando F9. O Excel recalculará automaticamente as fórmulas, exceto as tabelas. Uma nova planilha é criada chamando o método addworksheet () de um objeto de pasta de trabalho: Os métodos a seguir estão disponíveis por meio de uma nova planilha: Excel :: Writer :: XLSX oferece suporte a duas formas de notação para designar a posição de células: Notação linha-coluna E notação A1. A notação de linha-coluna usa um índice baseado em zero para linhas e colunas, enquanto a notação A1 usa a seqüência alfanumérica padrão do Excel de uma letra de coluna e uma linha com base em 1. Por exemplo: Notação de linha-coluna é útil se você estiver se referindo a células programaticamente: Notação de A1 é útil para configurar uma planilha manualmente e para trabalhar com fórmulas: Em fórmulas e métodos aplicáveis, você também pode usar a notação de coluna A: A Excel :: Writer :: XLSX :: O módulo de utilitário que está incluído na distribuição contém funções auxiliares para lidar com a notação A1, por exemplo: Para simplificar, as listas de parâmetros para as chamadas de método de planilha nas seções a seguir são dadas em termos de linha - coluna notação. Em todos os casos também é possível usar a notação A1. Nota: no Excel também é possível usar uma notação R1C1. Isso não é suportado pelo Excel :: Writer :: XLSX. Excel faz uma distinção entre tipos de dados como seqüências de caracteres, números, espaços em branco, fórmulas e hiperlinks. Para simplificar o processo de gravação de dados, o método write () atua como um alias geral para vários métodos mais específicos: A regra geral é que se os dados parecem algo, então algo é escrito. Aqui estão alguns exemplos em notação de linha e coluna A1: A regra 34looks like34 é definida por expressões regulares: writenumber () if token é um número baseado no seguinte regex: token writestring () se keepleadingzeros () for set e token for Um inteiro com zeros à esquerda com base no seguinte regex: token writeblank () se token for undef ou uma string em branco: undef. 3434 ou 3939. Writeurl () se o token é um URL http, https, ftp ou mailto com base nos seguintes regexes: token mf ou token writeurl () se token for uma referência de folha interna ou externa com base no seguinte regex: token writeformula () if the first O caractere de token é 3434. Writearrayformula () se o token corresponder. Writerow () se token é um array ref. Writecol () se token é um array ref de array refs. Writestring () se nenhuma das condições anteriores se aplicar. O parâmetro format é opcional. Ele deve ser um objeto Format válido, consulte 34CELL FORMATTING34: O método write () ignorará cadeias vazias ou undef tokens, a menos que um formato também seja fornecido. Como tal, você não precisa se preocupar com manuseio especial para valores vazios ou undef em seus dados. Veja também o método writeblank (). Um problema com o método write () é que, ocasionalmente, os dados parecem um número, mas você não quer que ele seja tratado como um número. Por exemplo, os códigos postais ou números de ID muitas vezes começam com um zero à esquerda. Se você gravar esses dados como um número, então o (s) zero (s) inicial será (ão) removido (s). Você pode alterar esse comportamento padrão usando o método keepleadingzeros (). Enquanto essa propriedade estiver no lugar, quaisquer inteiros com zeros à esquerda serão tratados como strings e os zeros serão preservados. Consulte a seção keepleadingzeros () para uma discussão completa sobre este problema. Você também pode adicionar seus próprios manipuladores de dados ao método write () usando addwritehandler (). O método write () também manipulará seqüências Unicode no formato UTF-8. Os métodos de gravação retornam: Escreve um inteiro ou um flutuador para a célula especificada por linha e coluna: Veja a nota sobre 34Cell notation34. O parâmetro format é opcional. Em geral, basta usar o método write (). Nota . Algumas versões do Excel 2007 não exibem os valores calculados de fórmulas escritas pelo Excel :: Writer :: XLSX. Aplicar todos os Service Packs disponíveis para o Excel deve corrigir isso. Escreva uma cadeia na célula especificada por linha e coluna: O tamanho máximo da cadeia é 32767 caracteres. No entanto, o segmento de seqüência máximo que o Excel pode exibir em uma célula é 1000. Todos os 32767 caracteres podem ser exibidos na barra de fórmulas. O parâmetro format é opcional. O método write () também manipulará strings no formato UTF-8. Consulte também os programas unicode. pl no diretório de exemplos da distro. Em geral, basta usar o método write (). No entanto, às vezes você pode querer usar o método writestring () para gravar dados que parecem um número, mas que você não deve ser tratado como um número. Por exemplo, códigos postais ou números de telefone: No entanto, se o usuário editar essa seqüência de caracteres, o Excel poderá convertê-la novamente em um número. Para contornar isso você pode usar o formato de texto do Excel: O método writerichstring () é usado para escrever strings com vários formatos. Por exemplo, para escrever a seqüência 34Esta é negrito e isso é itálico 34 você usaria o seguinte: A regra básica é quebrar a seqüência de caracteres em fragmentos e colocar um objeto de formato antes do fragmento que você deseja formatar. Por exemplo: Os fragmentos de cordas que não têm um formato recebem um formato padrão. Assim, por exemplo, ao escrever a string 34Some bold text34 você usaria o primeiro exemplo abaixo, mas seria equivalente ao segundo: Como no Excel, apenas as propriedades da fonte do formato, como nome da fonte, estilo, tamanho, sublinhado, cor e Efeitos são aplicados aos fragmentos de cordas. Outros recursos, como borda, fundo, quebra de texto e alinhamento devem ser aplicados à célula. O método writerichstring () permite que você faça isso usando o último argumento como um formato de célula (se for um objeto de formato). O exemplo a seguir centraliza uma seqüência de caracteres rica na célula: Consulte o exemplo de richstrings. pl na distribuição para obter mais exemplos. Como com writesting () o tamanho máximo de seqüência de caracteres é 32767 caracteres. Veja também a nota sobre a notação 34Cell34. Esse método altera o processamento padrão de inteiros com zeros à esquerda ao usar o método write (). O método write () usa expressões regulares para determinar o tipo de dados a serem gravados em uma planilha do Excel. Se os dados parecem um número, ele grava um número usando writenumber (). Um problema com esta abordagem é que, ocasionalmente, os dados parecem um número, mas você não quer que ele seja tratado como um número. Os códigos postais e os números de identificação, por exemplo, começam com um zero inicial. Se você gravar esses dados como um número, então o (s) zero (s) inicial será (ão) removido (s). Esse também é o comportamento padrão quando você insere dados manualmente no Excel. Para contornar isso você pode usar uma das três opções. Escreva um número formatado, escreva o número como uma string ou use o método keepleadingzeros () para alterar o comportamento padrão de write (): O código acima geraria uma planilha parecida com a seguinte: Os exemplos estão em lados diferentes das células Devido ao fato de que o Excel exibe seqüências com uma justificação à esquerda e números com uma justificação à direita por padrão. Você pode alterar isso usando um formato para justificar os dados, consulte 34CELL FORMATTING34. Deve-se notar que se o usuário edita os dados nos exemplos A3 e A4, as strings voltarão a números. Novamente, esse é o comportamento padrão do Excel39s. Para evitar isso, você pode usar o formato de texto: A propriedade keepleadingzeros () está desativada por padrão. O método keepleadingzeros () toma 0 ou 1 como argumento. O padrão é 1 se um argumento não for especificado: Consulte também o método addwritehandler (). Escreva uma célula em branco especificada por linha e coluna: Este método é utilizado para adicionar formatação a uma célula que não contém um valor de cadeia ou número. Excel diferencia entre uma célula 34Empty34 e uma 34Blank34 célula. Uma célula 34Empty34 é uma célula que não contém dados enquanto que uma célula 34Blank34 é uma célula que não contém dados mas contém formatação. Excel armazena células 34Blank34 mas ignora células 34Empty34. Como tal, se você escrever uma célula vazia sem formatação é ignorada: Este fato aparentemente desinteressante significa que você pode escrever matrizes de dados sem tratamento especial para undef ou valores de seqüência vazia. O método writerow () pode ser usado para gravar uma matriz 1D ou 2D de dados de uma só vez. Isso é útil para converter os resultados de uma consulta de banco de dados em uma planilha do Excel. Você deve passar uma referência para a matriz de dados em vez da matriz em si. O método write () é então chamado para cada elemento dos dados. Por exemplo: Nota: Por conveniência o método write () se comporta da mesma forma que writerow () se for passado uma referência de array. Portanto, as duas chamadas de método a seguir são equivalentes: Como com todos os métodos de gravação, o parâmetro de formato é opcional. Se um formato é especificado, ele é aplicado a todos os elementos da matriz de dados. As referências de matriz dentro dos dados serão tratadas como colunas. Isso permite que você escreva matrizes 2D de dados de uma só vez. Por exemplo: Produziria uma planilha da seguinte forma: Para gravar os dados em uma ordem de linha-coluna, consulte o método writecol () abaixo. Todos os valores undef nos dados serão ignorados a menos que um formato seja aplicado aos dados, caso em que uma célula em branco formatada será gravada. Em ambos os casos, o valor de linha ou coluna apropriado ainda será incrementado. Para saber mais sobre referências de matrizes, consulte perlref e perlreftut na documentação principal do Perl. Para saber mais sobre arranjos 2D ou 34 listas de listas34, consulte perllol. O método writerow () retorna o primeiro erro encontrado ao gravar os elementos dos dados ou zero se nenhum erro foi encontrado. Consulte os valores de retorno descritos para o método write () acima. Veja também o programa writearrays. pl no diretório examples da distro. O método writerow () permite a conversão idiomática a seguir de um arquivo de texto para um arquivo do Excel: O método writecol () pode ser usado para gravar uma matriz de dados 1D ou 2D de uma só vez. Isso é útil para converter os resultados de uma consulta de banco de dados em uma planilha do Excel. Você deve passar uma referência para a matriz de dados em vez da matriz em si. O método write () é então chamado para cada elemento dos dados. Por exemplo: Como com todos os métodos de gravação, o parâmetro format é opcional. Se um formato é especificado, ele é aplicado a todos os elementos da matriz de dados. As referências de matriz dentro dos dados serão tratadas como linhas. Isso permite que você escreva matrizes 2D de dados de uma só vez. Por exemplo: Produzia uma planilha da seguinte maneira: Para gravar os dados em uma ordem de linha de coluna, consulte o método writerow () acima. Todos os valores undef nos dados serão ignorados a menos que um formato seja aplicado aos dados, caso em que uma célula em branco formatada será gravada. Em ambos os casos, o valor de linha ou coluna apropriado ainda será incrementado. Conforme mencionado acima, o método write () pode ser usado como um sinônimo para writerow () e writerow () manipula refs de colunas aninhadas como colunas. Portanto, as duas chamadas de método a seguir são equivalentes, embora a chamada mais explícita para writecol () seja preferível para manutenção: Para saber mais sobre referências de matriz, consulte perlref e perlreftut na documentação principal do Perl. Para saber mais sobre arranjos 2D ou 34 listas de listas34, consulte perllol. O método writecol () retorna o primeiro erro encontrado ao gravar os elementos dos dados ou zero se nenhum erro foi encontrado. Consulte os valores de retorno descritos para o método write () acima. Veja também o programa writearrays. pl no diretório examples da distro. O método writedatetime () pode ser usado para escrever uma data ou hora para a célula especificada por linha e coluna: O datastring deve estar no seguinte formato: Isso está em conformidade com uma data ISO8601, mas deve-se notar que a gama completa de formatos ISO8601 Não são suportados. As seguintes variações no parâmetro de cadeia de datas são permitidas: Note que o T é necessário em todos os casos. Uma data deve sempre ter um formato. Caso contrário, ele aparecerá como um número, consulte 34DATA E HORA EM EXCEL34 e 34CELL FORMATTING34. Aqui está um exemplo típico: Datas válidas devem estar no intervalo de 1900-01-01 a 9999-12-31, para a época de 1900 e 1904-01-01 a 9999-12-31, para a época de 1904. Como com o Excel, as datas fora desses intervalos serão gravadas como uma seqüência de caracteres. Consulte também o programa datetime. pl no diretório de exemplos da distro. Escreva um hiperlink para um URL na célula especificada por linha e coluna. A hiperligação é composta por dois elementos: o rótulo visível eo link invisível. O rótulo visível é o mesmo que o link, a menos que um rótulo alternativo seja especificado. O parâmetro label é opcional. O rótulo é escrito usando o método write (). Portanto, é possível escrever strings, números ou fórmulas como rótulos. O formato parâmetro também é opcional, no entanto, sem um formato o link won39t olhar como um link. O formato sugerido é: Nota. Esse comportamento é diferente de Spreadsheet :: WriteExcel que fornece um formato de hiperlink padrão se um isn39t especificado pelo usuário. Existem quatro estilos de web suportados por URI39:. . Ftp: e mailto. Você pode exibir uma seqüência alternativa usando o parâmetro label: Se você deseja ter alguns outros dados de célula, como um número ou uma fórmula, você pode substituir a célula usando outra chamada para write (): Há dois URIs locais suportados: internal: e externo. Estes são utilizados para hiperligações para referências de folha de cálculo interna ou referências externas de pasta de trabalho e folha de cálculo: Todos estes tipos de URI são reconhecidos pelo método write (), consulte acima. Referências de planilha são normalmente do formulário Sheet1A1. Você também pode consultar um intervalo de planilha usando a notação padrão do Excel: Sheet1A1: B2. Em ligações externas, o livro e o nome da folha de cálculo devem ser separados pelo carácter: external: Workbook. xlsxSheet1A139. Você também pode vincular a um intervalo nomeado na planilha de destino. Por exemplo, digamos que você tenha um intervalo nomeado chamado myname na pasta de trabalho c: tempfoo. xlsx, você poderia vincular a ele da seguinte maneira: O Excel requer que os nomes de planilha contendo espaços ou caracteres não alfanuméricos sejam cadastrados como se segue 39Sales Data39A1. Se você precisa fazer isso em uma única seqüência de caracteres entre aspas, então você pode escapar das aspas simples 39 ou usar o operador de cotação q como descrito em perlop na documentação principal do Perl. Os links para arquivos de rede também são suportados. MSNovell Network files normally begin with two back slashes as follows NETWORKetc. In order to generate this in a single or double quoted string you will have to escape the backslashes, 39NETWORKetc39 . If you are using double quote strings then you should be careful to escape anything that looks like a metacharacter. For more information see perlfaq5: Why can39t I use 34C:tempfoo34 in DOS paths. Finally, you can avoid most of these quoting problems by using forward slashes. These are translated internally to backslashes: Note: Excel::Writer::XLSX will escape the following characters in URLs as required by Excel: s 34 60 62 unless the URL already contains xx style escapes. In which case it is assumed that the URL was escaped correctly by the user and will by passed directly to Excel. Excel limits hyperlink links and anchorlocations to 255 characters each. Write a formula or function to the cell specified by row and column : Array formulas are also supported: See also the writearrayformula() method below. If required, it is also possible to specify the calculated value of the formula. This is occasionally necessary when working with non-Excel applications that don39t calculate the value of the formula. The calculated value is added at the end of the argument list: However, this probably isn39t something that you will ever need to do. If you do use this feature then do so with care. Write an array formula to a cell range. In Excel an array formula is a formula that performs a calculation on a set of values. It can return a single value or a range of values. An array formula is indicated by a pair of braces around the formula: . If the array formula returns a single value then the first and last parameters should be the same: It this case however it is easier to just use the writeformula() or write() methods: For array formulas that return a range of values you must specify the range that the return values will be written to: If required, it is also possible to specify the calculated value of the formula. This is occasionally necessary when working with non-Excel applications that don39t calculate the value of the formula. However, using this parameter only writes a single value to the upper left cell in the result array. For a multi-cell array formula where the results are required, the other result values can be specified by using writenumber() to write to the appropriate cell: In addition, some early versions of Excel 2007 don39t calculate the values of array formulas when they aren39t supplied. Installing the latest Office Service Pack should fix this issue. See also the arrayformula. pl program in the examples directory of the distro. Note: Array formulas are not supported by Spreadsheet::WriteExcel. Write an Excel boolean value to the cell specified by row and column : A value that is true or false using Perl39s rules will be written as an Excel boolean TRUE or FALSE value. Deprecated. This is a Spreadsheet::WriteExcel method that is no longer required by Excel::Writer::XLSX. See below. Deprecated. This is a Spreadsheet::WriteExcel method that is no longer required by Excel::Writer::XLSX. In Spreadsheet::WriteExcel it was computationally expensive to write formulas since they were parsed by a recursive descent parser. The storeformula() and repeatformula() methods were used as a way of avoiding the overhead of repeated formulas by reusing a pre-parsed formula. In Excel::Writer::XLSX this is no longer necessary since it is just as quick to write a formula as it is to write a string or a number. The methods remain for backward compatibility but new Excel::Writer::XLSX programs shouldn39t use them. The writecomment() method is used to add a comment to a cell. A cell comment is indicated in Excel by a small red triangle in the upper right-hand corner of the cell. Moving the cursor over the red triangle will reveal the comment. The following example shows how to add a comment to a cell: As usual you can replace the row and column parameters with an A1 cell reference. See the note about 34Cell notation34 . The writecomment() method will also handle strings in UTF-8 format. In addition to the basic 3 argument form of writecomment() you can pass in several optional keyvalue pairs to control the format of the comment. For example: Most of these options are quite specific and in general the default comment behaves will be all that you need. However, should you need greater control over the format of the cell comment the following options are available: This option is used to indicate who is the author of the cell comment. Excel displays the author of the comment in the status bar at the bottom of the worksheet. This is usually of interest in corporate environments where several people might review and provide comments to a workbook. The default author for all cell comments can be set using the setcommentsauthor() method (see below). This option is used to make a cell comment visible when the worksheet is opened. The default behaviour in Excel is that comments are initially hidden. However, it is also possible in Excel to make individual or all comments visible. In Excel::Writer::XLSX individual comments can be made visible as follows: It is possible to make all comments in a worksheet visible using the showcomments() worksheet method (see below). Alternatively, if all of the cell comments have been made visible you can hide individual comments: This option is used to set the width of the cell comment box as a factor of the default width. This option is used to set the width of the cell comment box explicitly in pixels. This option is used to set the height of the cell comment box as a factor of the default height. This option is used to set the height of the cell comment box explicitly in pixels. This option is used to set the background colour of cell comment box. You can use one of the named colours recognised by Excel::Writer::XLSX or a Html style RRGGBB colour. See 34WORKING WITH COLOURS34 . This option is used to set the cell in which the comment will appear. By default Excel displays comments one cell to the right and one cell above the cell to which the comment relates. However, you can change this behaviour if you wish. In the following example the comment which would appear by default in cell D2 is moved to E2 . This option is used to set the row in which the comment will appear. See the startcell option above. The row is zero indexed. This option is used to set the column in which the comment will appear. See the startcell option above. The column is zero indexed. This option is used to change the x offset, in pixels, of a comment within a cell: This option is used to change the y offset, in pixels, of a comment within a cell: You can apply as many of these options as you require. Note about using options that adjust the position of the cell comment such as startcell, startrow, startcol, xoffset and yoffset . Excel only displays offset cell comments when they are displayed as 34visible34. Excel does not display hidden cells as moved when you mouse over them. Note about row height and comments . If you specify the height of a row that contains a comment then Excel::Writer::XLSX will adjust the height of the comment to maintain the default or user specified dimensions. However, the height of a row can also be adjusted automatically by Excel if the text wrap property is set or large fonts are used in the cell. This means that the height of the row is unknown to the module at run time and thus the comment box is stretched with the row. Use the setrow() method to specify the row height explicitly and avoid this problem. This method is used to make all cell comments visible when a worksheet is opened. Individual comments can be made visible using the visible parameter of the writecomment method (see above): If all of the cell comments have been made visible you can hide individual comments as follows: This method is used to set the default author of all cell comments. Individual comment authors can be set using the author parameter of the writecomment method (see above). The default comment author is an empty string, 3939. if no author is specified. This method is used to extend the Excel::Writer::XLSX write() method to handle user defined data. If you refer to the section on write() above you will see that it acts as an alias for several more specific write methods. However, it doesn39t always act in exactly the way that you would like it to. One solution is to filter the input data yourself and call the appropriate write method. Another approach is to use the addwritehandler() method to add your own automated behaviour to write() . The addwritehandler() method take two arguments, re. a regular expression to match incoming data and coderef a callback function to handle the matched data: (In the these examples the qr operator is used to quote the regular expression strings, see perlop for more details). The method is used as follows. say you wished to write 7 digit ID numbers as a string so that any leading zeros were preserved, you could do something like the following: You could also use the keepleadingzeros() method for this. Then if you call write() with an appropriate string it will be handled automatically: The callback function will receive a reference to the calling worksheet and all of the other arguments that were passed to write(). The callback will see an argument list that looks like the following: Your callback should return() the return value of the write method that was called or undef to indicate that you rejected the match and want write() to continue as normal. So for example if you wished to apply the previous filter only to ID values that occur in the first column you could modify your callback function as follows: Now, you will get different behaviour for the first column and other columns: You may add more than one handler in which case they will be called in the order that they were added. Note, the addwritehandler() method is particularly suited for handling dates. See the writehandler 1-4 programs in the examples directory for further examples. This method can be used to insert a image into a worksheet. The image can be in PNG, JPEG or BMP format. The x. y. xscale and yscale parameters are optional. The parameters x and y can be used to specify an offset from the top left hand corner of the cell specified by row and col. The offset values are in pixels. The offsets can be greater than the width or height of the underlying cell. This can be occasionally useful if you wish to align two or more images relative to the same cell. The parameters xscale and yscale can be used to scale the inserted image horizontally and vertically: Note: you must call setrow() or setcolumn() before insertimage() if you wish to change the default dimensions of any of the rows or columns that the image occupies. The height of a row can also change if you use a font that is larger than the default. This in turn will affect the scaling of your image. To avoid this you should explicitly set the height of the row using setrow() if it contains a font size that will change the row height. BMP images must be 24 bit, true colour, bitmaps. In general it is best to avoid BMP images since they aren39t compressed. This method can be used to insert a Chart object into a worksheet. The Chart must be created by the addchart() Workbook method and it must have the embedded option set. See addchart() for details on how to create the Chart object and Excel::Writer::XLSX::Chart for details on how to configure it. See also the chart. pl programs in the examples directory of the distro. The x. y. xscale and yscale parameters are optional. The parameters x and y can be used to specify an offset from the top left hand corner of the cell specified by row and col. The offset values are in pixels. The parameters xscale and yscale can be used to scale the inserted chart horizontally and vertically: This method can be used to insert a Shape object into a worksheet. The Shape must be created by the addshape() Workbook method. See addshape() for details on how to create the Shape object and Excel::Writer::XLSX::Shape for details on how to configure it. The x. y. xscale and yscale parameters are optional. The parameters x and y can be used to specify an offset from the top left hand corner of the cell specified by row and col. The offset values are in pixels. The parameters xscale and yscale can be used to scale the inserted shape horizontally and vertically: See also the shape. pl programs in the examples directory of the distro. insertbutton( row, col, ) The insertbutton() method can be used to insert an Excel form button into a worksheet. This method is generally only useful when used in conjunction with the Workbook addvbaproject() method to tie the button to a macro from an embedded VBA project: The properties of the button that can be set are: This option is used to set the macro that the button will invoke when the user clicks on it. The macro should be included using the Workbook addvbaproject() method shown above. The default macro is ButtonXClick where X is the button number. This option is used to set the caption on the button. The default is Button X where X is the button number. This option is used to set the width of the button in pixels. The default button width is 64 pixels which is the width of a default cell. This option is used to set the height of the button in pixels. The default button height is 20 pixels which is the height of a default cell. This option is used to set the width of the button as a factor of the default width. This option is used to set the height of the button as a factor of the default height. This option is used to change the x offset, in pixels, of a button within a cell: This option is used to change the y offset, in pixels, of a comment within a cell. Note: Button is the only Excel form element that is available in Excel::Writer::XLSX. Form elements represent a lot of work to implement and the underlying VML syntax isn39t very much fun. The datavalidation() method is used to construct an Excel data validation or to limit the user input to a dropdown list of values. This method contains a lot of parameters and is described in detail in a separate section 34DATA VALIDATION IN EXCEL34 . See also the datavalidate. pl program in the examples directory of the distro The conditionalformatting() method is used to add formatting to a cell or range of cells based on user defined criteria. This method contains a lot of parameters and is described in detail in a separate section 34CONDITIONAL FORMATTING IN EXCEL34 . See also the conditionalformat. pl program in the examples directory of the distro The addsparkline() worksheet method is used to add sparklines to a cell or a range of cells. This method contains a lot of parameters and is described in detail in a separate section 34SPARKLINES IN EXCEL34 . See also the sparklines1.pl and sparklines2.pl example programs in the examples directory of the distro. Note: Sparklines are a feature of Excel 2010 only. You can write them to an XLSX file that can be read by Excel 2007 but they won39t be displayed. The addtable() method is used to group a range of cells into an Excel Table. This method contains a lot of parameters and is described in detail in a separate section 34TABLES IN EXCEL34 . See also the tables. pl program in the examples directory of the distro The getname() method is used to retrieve the name of a worksheet. For example: For reasons related to the design of Excel::Writer::XLSX and to the internals of Excel there is no setname() method. The only way to set the worksheet name is via the addworksheet() method. The activate() method is used to specify which worksheet is initially visible in a multi-sheet workbook: This is similar to the Excel VBA activate method. More than one worksheet can be selected via the select() method, see below, however only one worksheet can be active. The default active worksheet is the first worksheet. The select() method is used to indicate that a worksheet is selected in a multi-sheet workbook: A selected worksheet has its tab highlighted. Selecting worksheets is a way of grouping them together so that, for example, several worksheets could be printed in one go. A worksheet that has been activated via the activate() method will also appear as selected. The hide() method is used to hide a worksheet: You may wish to hide a worksheet in order to avoid confusing a user with intermediate data or calculations. A hidden worksheet can not be activated or selected so this method is mutually exclusive with the activate() and select() methods. In addition, since the first worksheet will default to being the active worksheet, you cannot hide the first worksheet without activating another sheet: The activate() method determines which worksheet is initially selected. However, if there are a large number of worksheets the selected worksheet may not appear on the screen. To avoid this you can select which is the leftmost visible worksheet using setfirstsheet() : This method is not required very often. The default value is the first worksheet. The protect() method is used to protect a worksheet from modification: The protect() method also has the effect of enabling a cell39s locked and hidden properties if they have been set. A locked cell cannot be edited and this property is on by default for all cells. A hidden cell will display the results of a formula but not the formula itself. See the protection. pl program in the examples directory of the distro for an illustrative example and the setlocked and sethidden format methods in 34CELL FORMATTING34 . You can optionally add a password to the worksheet protection: Passing the empty string 3939 is the same as turning on protection without a password. Note, the worksheet level password in Excel provides very weak protection. It does not encrypt your data and is very easy to deactivate. Full workbook encryption is not supported by Excel::Writer::XLSX since it requires a completely different file format and would take several man months to implement. You can specify which worksheet elements you wish to protect by passing a hashref with any or all of the following keys: The default boolean values are shown above. Individual elements can be protected as follows: This method can be used to specify which cell or cells are selected in a worksheet. The most common requirement is to select a single cell, in which case lastrow and lastcol can be omitted. The active cell within a selected range is determined by the order in which first and last are specified. It is also possible to specify a cell or a range using A1 notation. See the note about 34Cell notation34 . The default cell selections is (0, 0), 39A139. This method can be used to change the default properties of a row. All parameters apart from row are optional. The most common use for this method is to change the height of a row: If you wish to set the format without changing the height you can pass undef as the height parameter: The format parameter will be applied to any cells in the row that don39t have a format. For example If you wish to define a row format in this way you should call the method before any calls to write(). Calling it afterwards will overwrite any format that was previously specified. The hidden parameter should be set to 1 if you wish to hide a row. This can be used, for example, to hide intermediary steps in a complicated calculation: The level parameter is used to set the outline level of the row. Outlines are described in 34OUTLINES AND GROUPING IN EXCEL34. Adjacent rows with the same outline level are grouped together into a single outline. The following example sets an outline level of 1 for rows 1 and 2 (zero-indexed): The hidden parameter can also be used to hide collapsed outlined rows when used in conjunction with the level parameter. For collapsed outlines you should also indicate which row has the collapsed symbol using the optional collapsed parameter. For a more complete example see the outline. pl and outlinecollapsed. pl programs in the examples directory of the distro. Excel allows up to 7 outline levels. Therefore the level parameter should be in the range 0 60 level 60 7 . This method can be used to change the default properties of a single column or a range of columns. All parameters apart from firstcol and lastcol are optional. If setcolumn() is applied to a single column the value of firstcol and lastcol should be the same. In the case where lastcol is zero it is set to the same value as firstcol . It is also possible, and generally clearer, to specify a column range using the form of A1 notation used for columns. See the note about 34Cell notation34 . The width corresponds to the column width value that is specified in Excel. It is approximately equal to the length of a string in the default font of Calibri 11. Unfortunately, there is no way to specify 34AutoFit34 for a column in the Excel file format. This feature is only available at runtime from within Excel. As usual the format parameter is optional, for additional information, see 34CELL FORMATTING34. If you wish to set the format without changing the width you can pass undef as the width parameter: The format parameter will be applied to any cells in the column that don39t have a format. For example If you wish to define a column format in this way you should call the method before any calls to write(). If you call it afterwards it won39t have any effect. A default row format takes precedence over a default column format The hidden parameter should be set to 1 if you wish to hide a column. This can be used, for example, to hide intermediary steps in a complicated calculation: The level parameter is used to set the outline level of the column. Outlines are described in 34OUTLINES AND GROUPING IN EXCEL34. Adjacent columns with the same outline level are grouped together into a single outline. The following example sets an outline level of 1 for columns B to G: The hidden parameter can also be used to hide collapsed outlined columns when used in conjunction with the level parameter. For collapsed outlines you should also indicate which row has the collapsed symbol using the optional collapsed parameter. For a more complete example see the outline. pl and outlinecollapsed. pl programs in the examples directory of the distro. Excel allows up to 7 outline levels. Therefore the level parameter should be in the range 0 60 level 60 7 . The setdefaultrow() method is used to set the limited number of default row properties allowed by Excel. These are the default height and the option to hide unused rows. The option to hide unused rows is used by Excel as an optimisation so that the user can hide a large number of rows without generating a very large file with an entry for each hidden row. See the hiderowcol. pl example program. The outlinesettings() method is used to control the appearance of outlines in Excel. Outlines are described in 34OUTLINES AND GROUPING IN EXCEL34 . The visible parameter is used to control whether or not outlines are visible. Setting this parameter to 0 will cause all outlines on the worksheet to be hidden. They can be unhidden in Excel by means of the 34Show Outline Symbols34 command button. The default setting is 1 for visible outlines. The symbolsbelow parameter is used to control whether the row outline symbol will appear above or below the outline level bar. The default setting is 1 for symbols to appear below the outline level bar. The symbolsright parameter is used to control whether the column outline symbol will appear to the left or the right of the outline level bar. The default setting is 1 for symbols to appear to the right of the outline level bar. The autostyle parameter is used to control whether the automatic outline generator in Excel uses automatic styles when creating an outline. This has no effect on a file generated by Excel::Writer::XLSX but it does have an effect on how the worksheet behaves after it is created. The default setting is 0 for 34Automatic Styles34 to be turned off. The default settings for all of these parameters correspond to Excel39s default parameters. The worksheet parameters controlled by outlinesettings() are rarely used. This method can be used to divide a worksheet into horizontal or vertical regions known as panes and to also 34freeze34 these panes so that the splitter bars are not visible. This is the same as the Window-62Freeze Panes menu command in Excel The parameters row and col are used to specify the location of the split. It should be noted that the split is specified at the top or left of a cell and that the method uses zero based indexing. Therefore to freeze the first row of a worksheet it is necessary to specify the split at row 2 (which is 1 as the zero-based index). This might lead you to think that you are using a 1 based index but this is not the case. You can set one of the row and col parameters as zero if you do not want either a vertical or horizontal split. The parameters toprow and leftcol are optional. They are used to specify the top-most or left-most visible row or column in the scrolling region of the panes. For example to freeze the first row and to have the scrolling region begin at row twenty: You cannot use A1 notation for the toprow and leftcol parameters. See also the panes. pl program in the examples directory of the distribution. This method can be used to divide a worksheet into horizontal or vertical regions known as panes. This method is different from the freezepanes() method in that the splits between the panes will be visible to the user and each pane will have its own scroll bars. The parameters y and x are used to specify the vertical and horizontal position of the split. The units for y and x are the same as those used by Excel to specify row height and column width. However, the vertical and horizontal units are different from each other. Therefore you must specify the y and x parameters in terms of the row heights and column widths that you have set or the default values which are 15 for a row and 8.43 for a column. You can set one of the y and x parameters as zero if you do not want either a vertical or horizontal split. The parameters toprow and leftcol are optional. They are used to specify the top-most or left-most visible row or column in the bottom-right pane. You cannot use A1 notation with this method. See also the freezepanes() method and the panes. pl program in the examples directory of the distribution. The mergerange() method allows you to merge cells that contain other types of alignment in addition to the merging: mergerange() writes its token argument using the worksheet write() method. Therefore it will handle numbers, strings, formulas or urls as required. If you need to specify the required write() method use the mergerangetype() method, see below. The full possibilities of this method are shown in the merge3.pl to merge6.pl programs in the examples directory of the distribution. The mergerange() method, see above, uses write() to insert the required data into to a merged range. However, there may be times where this isn39t what you require so as an alternative the mergerangetype () method allows you to specify the type of data you wish to write. For example: The type must be one of the following, which corresponds to a write() method: Any arguments after the range should be whatever the appropriate method accepts: Note, you must always pass a format object as an argument, even if it is a default format. Set the worksheet zoom factor in the range 10 60 scale 60 400 : The default zoom factor is 100. You cannot zoom to 34Selection34 because it is calculated by Excel at run-time. Note, setzoom() does not affect the scale of the printed page. For that you should use setprintscale() . The righttoleft() method is used to change the default direction of the worksheet from left-to-right, with the A1 cell in the top left, to right-to-left, with the A1 cell in the top right. This is useful when creating Arabic, Hebrew or other near or far eastern worksheets that use right-to-left as the default direction. The hidezero() method is used to hide any zero values that appear in cells. In Excel this option is found under Tools-62Options-62View. The settabcolor() method is used to change the colour of the worksheet tab. You can use one of the standard colour names provided by the Format object or a Html style RRGGBB colour. See 34WORKING WITH COLOURS34 . See the tabcolors. pl program in the examples directory of the distro. This method allows an autofilter to be added to a worksheet. An autofilter is a way of adding drop down lists to the headers of a 2D range of worksheet data. This allows users to filter the data based on simple criteria so that some data is shown and some is hidden. To add an autofilter to a worksheet: Filter conditions can be applied using the filtercolumn() or filtercolumnlist() method. See the autofilter. pl program in the examples directory of the distro for a more detailed example. The filtercolumn method can be used to filter columns in a autofilter range based on simple conditions. NOTE: It isn39t sufficient to just specify the filter condition. You must also hide any rows that don39t match the filter condition. Rows are hidden using the setrow() visible parameter. Excel::Writer::XLSX cannot do this automatically since it isn39t part of the file format. See the autofilter. pl program in the examples directory of the distro for an example. The conditions for the filter are specified using simple expressions: The column parameter can either be a zero indexed column number or a string column name. The following operators are available: The operator synonyms are just syntactic sugar to make you more comfortable using the expressions. It is important to remember that the expressions will be interpreted by Excel and not by perl. An expression can comprise a single statement or two statements separated by the and and or operators. For example: Filtering of blank or non-blank data can be achieved by using a value of Blanks or NonBlanks in the expression: Excel also allows some simple string matching operations: You can also use to match any character or number and. to match any single character or number. No other regular expression quantifier is supported by Excel39s filters. Excel39s regular expression characters can be escaped using The placeholder variable x in the above examples can be replaced by any simple string. The actual placeholder name is ignored internally so the following are all equivalent: Also, note that a filter condition can only be applied to a column in a range specified by the autofilter() Worksheet method. See the autofilter. pl program in the examples directory of the distro for a more detailed example. Note Spreadsheet::WriteExcel supports Top 10 style filters. These aren39t currently supported by Excel::Writer::XLSX but may be added later. Prior to Excel 2007 it was only possible to have either 1 or 2 filter conditions such as the ones shown above in the filtercolumn method. Excel 2007 introduced a new list style filter where it is possible to specify 1 or more 39or39 style criteria. For example if your column contained data for the first six months the initial data would be displayed as all selected as shown on the left. Then if you selected 39March39, 39April39 and 39May39 they would be displayed as shown on the right. The filtercolumnlist() method can be used to represent these types of filters: The column parameter can either be a zero indexed column number or a string column name. One or more criteria can be selected: NOTE: It isn39t sufficient to just specify the filter condition. You must also hide any rows that don39t match the filter condition. Rows are hidden using the setrow() visible parameter. Excel::Writer::XLSX cannot do this automatically since it isn39t part of the file format. See the autofilter. pl program in the examples directory of the distro for an example. The convertdatetime() method is used internally by the writedatetime() method to convert date strings to a number that represents an Excel date and time. It is exposed as a public method for utility purposes. The datestring format is detailed in the writedatetime() method. The Worksheet setvbaname() method can be used to set the VBA codename for the worksheet (there is a similar method for the workbook VBA name). This is sometimes required when a vbaProject macro included via addvbaproject() refers to the worksheet. The default Excel VBA name of Sheet1. etc. is used if a user defined name isn39t specified. Page set-up methods affect the way that a worksheet looks when it is printed. They control features such as page headers and footers and margins. These methods are really just standard worksheet methods. They are documented here in a separate section for the sake of clarity. The following methods are available for page set-up: A common requirement when working with Excel::Writer::XLSX is to apply the same page set-up features to all of the worksheets in a workbook. To do this you can use the sheets() method of the workbook class to access the array of worksheets in a workbook: This method is used to set the orientation of a worksheet39s printed page to landscape: This method is used to set the orientation of a worksheet39s printed page to portrait. The default worksheet orientation is portrait, so you won39t generally need to call this method. This method is used to display the worksheet in 34Page ViewLayout34 mode. This method is used to set the paper format for the printed output of a worksheet. The following paper styles are available: Note, it is likely that not all of these paper types will be available to the end user since it will depend on the paper formats that the user39s printer supports. Therefore, it is best to stick to standard paper types. If you do not specify a paper type the worksheet will print using the printer39s default paper. Center the worksheet data horizontally between the margins on the printed page: Center the worksheet data vertically between the margins on the printed page: There are several methods available for setting the worksheet margins on the printed page: All of these methods take a distance in inches as a parameter. Note: 1 inch 25.4mm. -) The default left and right margin is 0.7 inch. The default top and bottom margin is 0.75 inch. Note, these defaults are different from the defaults used in the binary file format by Spreadsheet::WriteExcel. Headers and footers are generated using a string which is a combination of plain text and control characters. The margin parameter is optional. The available control character are: Text in headers and footers can be justified (aligned) to the left, center and right by prefixing the text with the control characters 38L. 38C and 38R . For example (with ASCII art representation of the results): For simple text, if you do not specify any justification the text will be centred. However, you must prefix the text with 38C if you specify a font name or any other formatting: You can have text in each of the justification regions: The information control characters act as variables that Excel will update as the workbook or worksheet changes. Times and dates are in the users default format: Images can be inserted using the options shown below. Each image must have a placeholder in header string using the 38Picture or 38G control characters: You can specify the font size of a section of the text by prefixing it with the control character 38n where n is the font size: You can specify the font of a section of the text by prefixing it with the control sequence 3834font, style34 where fontname is a font name such as 34Courier New34 or 34Times New Roman34 and style is one of the standard Windows font descriptions: 34Regular34, 34Italic34, 34Bold34 or 34Bold Italic34: It is possible to combine all of these features together to create sophisticated headers and footers. As an aid to setting up complicated headers and footers you can record a page set-up as a macro in Excel and look at the format strings that VBA produces. Remember however that VBA uses two double quotes 3434 to indicate a single double quote. For the last example above the equivalent VBA code looks like this: To include a single literal ampersand 38 in a header or footer you should use a double ampersand 3838 : As stated above the margin parameter is optional. As with the other margins the value should be in inches. The default header and footer margin is 0.3 inch. Note, the default margin is different from the default used in the binary file format by Spreadsheet::WriteExcel. The header and footer margin size can be set as follows: The header and footer margins are independent of the top and bottom margins. The available options are: imageleft The path to the image. Requires a 38G or 38Picture placeholder. imagecenter Same as above. imageright Same as above. scalewithdoc Scale header with document. Defaults to true. alignwithmargins Align header to margins. Defaults to true. The image options must have an accompanying 38Picture or 38G control character in the header string: Note, the header or footer string must be less than 255 characters. Strings longer than this will not be written and a warning will be generated. The setheader() method can also handle Unicode strings in UTF-8 format. See, also the headers. pl program in the examples directory of the distribution. The syntax of the setfooter() method is the same as setheader(). see above. Set the number of rows to repeat at the top of each printed page. For large Excel documents it is often desirable to have the first row or rows of the worksheet print out at the top of each page. This can be achieved by using the repeatrows() method. The parameters firstrow and lastrow are zero based. The lastrow parameter is optional if you only wish to specify one row: Set the columns to repeat at the left hand side of each printed page. For large Excel documents it is often desirable to have the first column or columns of the worksheet print out at the left hand side of each page. This can be achieved by using the repeatcolumns() method. The parameters firstcolumn and lastcolumn are zero based. The lastcolumn parameter is optional if you only wish to specify one column. You can also specify the columns using A1 column notation, see the note about 34Cell notation34 . This method is used to hide the gridlines on the screen and printed page. Gridlines are the lines that divide the cells on a worksheet. Screen and printed gridlines are turned on by default in an Excel worksheet. If you have defined your own cell borders you may wish to hide the default gridlines. The following values of option are valid: If you don39t supply an argument or use undef the default option is 1, i. e. only the printed gridlines are hidden. Set the option to print the row and column headers on the printed page. An Excel worksheet looks something like the following The headers are the letters and numbers at the top and the left of the worksheet. Since these headers serve mainly as a indication of position on the worksheet they generally do not appear on the printed page. If you wish to have them printed you can use the printrowcolheaders() method : Do not confuse these headers with page headers as described in the setheader() section above. This method is used to specify the area of the worksheet that will be printed. All four parameters must be specified. You can also use A1 notation, see the note about 34Cell notation34 . The printacross method is used to change the default print direction. This is referred to by Excel as the sheet 34page order34. The default page order is shown below for a worksheet that extends over 4 pages. The order is called 34down then across34: However, by using the printacross method the print order will be changed to 34across then down34: The fittopages() method is used to fit the printed area to a specific number of pages both vertically and horizontally. If the printed area exceeds the specified number of pages it will be scaled down to fit. This guarantees that the printed area will always appear on the specified number of pages even if the page size or margins change. The print area can be defined using the printarea() method as described above. A common requirement is to fit the printed output to n pages wide but have the height be as long as necessary. To achieve this set the height to zero: Note that although it is valid to use both fittopages() and setprintscale() on the same worksheet only one of these options can be active at a time. The last method call made will set the active option. Note that fittopages() will override any manual page breaks that are defined in the worksheet. Note: When using fittopages() it may also be required to set the printer paper size using setpaper() or else Excel will default to 34US Letter34. The setstartpage() method is used to set the number of the starting page when the worksheet is printed out. The default value is 1. Set the scale factor of the printed page. Scale factors in the range 10 60 scale 60 400 are valid: The default scale factor is 100. Note, setprintscale() does not affect the scale of the visible page in Excel. For that you should use setzoom() . Note also that although it is valid to use both fittopages() and setprintscale() on the same worksheet only one of these options can be active at a time. The last method call made will set the active option. Set the option to print the worksheet in black and white: Add horizontal page breaks to a worksheet. A page break causes all the data that follows it to be printed on the next page. Horizontal page breaks act between rows. To create a page break between rows 20 and 21 you must specify the break at row 21. However in zero index notation this is actually row 20. So you can pretend for a small while that you are using 1 index notation: The sethpagebreaks() method will accept a list of page breaks and you can call it more than once: Note: If you specify the 34fit to page34 option via the fittopages() method it will override all manual page breaks. There is a silent limitation of about 1000 horizontal page breaks per worksheet in line with an Excel internal limitation. Add vertical page breaks to a worksheet. A page break causes all the data that follows it to be printed on the next page. Vertical page breaks act between columns. To create a page break between columns 20 and 21 you must specify the break at column 21. However in zero index notation this is actually column 20. So you can pretend for a small while that you are using 1 index notation: The setvpagebreaks() method will accept a list of page breaks and you can call it more than once: Note: If you specify the 34fit to page34 option via the fittopages() method it will override all manual page breaks. This section describes the methods and properties that are available for formatting cells in Excel. The properties of a cell that can be formatted include: fonts, colours, patterns, borders, alignment and number formatting. Cell formatting is defined through a Format object. Format objects are created by calling the workbook addformat() method as follows: The format object holds all the formatting properties that can be applied to a cell, a row or a column. The process of setting these properties is discussed in the next section. Once a Format object has been constructed and its properties have been set it can be passed as an argument to the worksheet write methods as follows: Formats can also be passed to the worksheet setrow() and setcolumn() methods to define the default property for a row or column. The following table shows the Excel format categories, the formatting properties that can be applied and the equivalent object method: There are two ways of setting Format properties: by using the object method interface or by setting the property directly. For example, a typical use of the method interface would be as follows: By comparison the properties can be set directly by passing a hash of properties to the Format constructor: or after the Format has been constructed by means of the setformatproperties() method as follows: You can also store the properties in one or more named hashes and pass them to the required method: The provision of two ways of setting properties might lead you to wonder which is the best way. The method mechanism may be better if you prefer setting properties via method calls (which the author did when the code was first written) otherwise passing properties to the constructor has proved to be a little more flexible and self documenting in practice. An additional advantage of working with property hashes is that it allows you to share formatting between workbook objects as shown in the example above. The PerlTk style of adding properties is also supported: The default format is Calibri 11 with all other properties off. Each unique format in Excel::Writer::XLSX must have a corresponding Format object. It isn39t possible to use a Format with a write() method and then redefine the Format for use at a later stage. This is because a Format is applied to a cell not in its current state but in its final state. Consider the following example: Cell A1 is assigned the Format format which is initially set to the colour red. However, the colour is subsequently set to green. When Excel displays Cell A1 it will display the final state of the Format which in this case will be the colour green. In general a method call without an argument will turn a property on, for example: The Format object methods are described in more detail in the following sections. In addition, there is a Perl program called formats. pl in the examples directory of the WriteExcel distribution. This program creates an Excel workbook called formats. xlsx which contains examples of almost all the format types. The following Format methods are available: The above methods can also be applied directly as properties. For example format-62setbold() is equivalent to workbook-62addformat(bold 62 1) . The properties of an existing Format object can be also be set by means of setformatproperties() : However, this method is here mainly for legacy reasons. It is preferable to set the properties in the format constructor: Specify the font used: Excel can only display fonts that are installed on the system that it is running on. Therefore it is best to use the fonts that come as standard such as 39Calibri39, 39Times New Roman39 and 39Courier New39. See also the Fonts worksheet created by formats. pl Set the font size. Excel adjusts the height of a row to accommodate the largest font size in the row. You can also explicitly specify the height of a row using the setrow() worksheet method. Set the font colour. The setcolor() method is used as follows: Note: The setcolor() method is used to set the colour of the font in a cell. To set the colour of a cell use the setbgcolor() and setpattern() methods. For additional examples see the 39Named colors39 and 39Standard colors39 worksheets created by formats. pl in the examples directory. Set the bold property of the font: Set the italic property of the font: This method is used to define the numerical format of a number in Excel. It controls whether a number is displayed as an integer, a floating point number, a date, a currency value or some other user defined format. The numerical format of a cell can be specified by using a format string or an index to one of Excel39s built-in formats: Using format strings you can define very sophisticated formatting of numbers. The number system used for dates is described in 34DATES AND TIME IN EXCEL34 . The colour format should have one of the following values: Alternatively you can specify the colour based on a colour index as follows: Color n. where n is a standard Excel colour index - 7. See the 39Standard colors39 worksheet created by formats. pl. For more information refer to the documentation on formatting in the docs directory of the Excel::Writer::XLSX distro, the Excel on-line help or office. microsoften-gbassistanceHP051995001033.aspx . You should ensure that the format string is valid in Excel prior to using it in WriteExcel. Excel39s built-in formats are shown in the following table: For examples of these formatting codes see the 39Numerical formats39 worksheet created by formats. pl. See also the numberformats1.html and the numberformats2.html documents in the docs directory of the distro. Note 1. Numeric formats 23 to 36 are not documented by Microsoft and may differ in international versions. Note 2. The dollar sign appears as the defined local currency symbol. This property can be used to prevent modification of a cells contents. Following Excel39s convention, cell locking is turned on by default. However, it only has an effect if the worksheet has been protected, see the worksheet protect() method. Note: This offers weak protection even with a password, see the note in relation to the protect() method. This property is used to hide a formula while still displaying its result. This is generally used to hide complex calculations from end users who are only interested in the result. It only has an effect if the worksheet has been protected, see the worksheet protect() method. Note: This offers weak protection even with a password, see the note in relation to the protect() method. This method is used to set the horizontal and vertical text alignment within a cell. Vertical and horizontal alignments can be combined. The method is used as follows: Text can be aligned across two or more adjacent cells using the centeracross property. However, for genuine merged cells it is better to use the mergerange() worksheet method. The vjustify (vertical justify) option can be used to provide automatic text wrapping in a cell. The height of the cell will be adjusted to accommodate the wrapped text. To specify where the text wraps use the settextwrap() method. For further examples see the 39Alignment39 worksheet created by formats. pl. Text can be aligned across two or more adjacent cells using the setcenteracross() method. This is an alias for the setalign(39centeracross39) method call. Only one cell should contain the text, the other cells should be blank: See also the merge1.pl to merge6.pl programs in the examples directory and the mergerange() method. Here is an example using the text wrap property, the escape character n is used to indicate the end of line: Excel will adjust the height of the row to accommodate the wrapped text. A similar effect can be obtained without newlines using the setalign(39vjustify39) method. See the textwrap. pl program in the examples directory. Set the rotation of the text in a cell. The rotation can be any angle in the range -90 to 90 degrees. The angle 270 is also supported. This indicates text where the letters run from top to bottom. This method can be used to indent text. The argument, which should be an integer, is taken as the level of indentation: Indentation is a horizontal alignment property. It will override any other horizontal properties but it can be used in conjunction with vertical properties. This method can be used to shrink text so that it fits in a cell. Only applies to Far Eastern versions of Excel. Set the background pattern of a cell. Examples of the available patterns are shown in the 39Patterns39 worksheet created by formats. pl. However, it is unlikely that you will ever need anything other than Pattern 1 which is a solid fill of the background color. The setbgcolor() method can be used to set the background colour of a pattern. Patterns are defined via the setpattern() method. If a pattern hasn39t been defined then a solid fill pattern is used as the default. Here is an example of how to set up a solid fill in a cell: For further examples see the 39Patterns39 worksheet created by formats. pl. The setfgcolor() method can be used to set the foreground colour of a pattern. For further examples see the 39Patterns39 worksheet created by formats. pl. A cell border is comprised of a border on the bottom, top, left and right. These can be set to the same value using setborder() or individually using the relevant method calls shown above. The following shows the border styles sorted by Excel::Writer::XLSX index number: The following shows the borders sorted by style: The following shows the borders in the order shown in the Excel Dialog. Examples of the available border styles are shown in the 39Borders39 worksheet created by formats. pl. Set the colour of the cell borders. A cell border is comprised of a border on the bottom, top, left and right. These can be set to the same colour using setbordercolor() or individually using the relevant method calls shown above. Examples of the border styles and colours are shown in the 39Borders39 worksheet created by formats. pl. Set the diagonal border type for the cell. Three types of diagonal borders are available in Excel: Set the diagonal border style. Same as the parameter to setborder() above. Set the colour of the diagonal cell border: This method is used to copy all of the properties from one Format object to another: The copy() method is only useful if you are using the method interface to Format properties. It generally isn39t required if you are setting Format properties directly using hashes. Note: this is not a copy constructor, both objects must exist prior to copying. The following is a brief introduction to handling Unicode in Excel::Writer::XLSX . For a more general introduction to Unicode handling in Perl see perlunitut and perluniintro . Excel::Writer::XLSX writer differs from Spreadsheet::WriteExcel in that it only handles Unicode data in UTF-8 format and doesn39t try to handle legacy UTF-16 Excel formats. If the data is in UTF-8 format then Excel::Writer::XLSX will handle it automatically. If you are dealing with non-ASCII characters that aren39t in UTF-8 then perl provides useful tools in the guise of the Encode module to help you to convert to the required format. For example: Alternatively you can read data from an encoded file and convert it to UTF-8 as you read it in: If the program contains UTF-8 text then you will also need to add use utf8 to the includes: See also the unicode. pl programs in the examples directory of the distro. Throughout Excel::Writer::XLSX colours can be specified using a Html style RRGGBB value. For example with a Format object: For backward compatibility a limited number of color names are supported: The color names supported are: See also colors. pl in the examples directory. There are two important things to understand about dates and times in Excel: These two points are explained in more detail below along with some suggestions on how to convert times and dates to the required format. If you write a date string with write() then all you will get is a string: Dates and times in Excel are represented by real numbers, for example 34Jan 1 2001 12:30 AM34 is represented by the number 36892.521. The integer part of the number stores the number of days since the epoch and the fractional part stores the percentage of the day. A date or time in Excel is just like any other number. To have the number display as a date you must apply an Excel number format to it. Here are some examples. Excel::Writer::XLSX doesn39t automatically convert input date strings into Excel39s formatted date numbers due to the large number of possible date formats and also due to the possibility of misinterpretation. For example, does 020304 mean March 2 2004, February 3 2004 or even March 4 2002. Therefore, in order to handle dates you will have to convert them to numbers and apply an Excel format. Some methods for converting dates are listed in the next section. The most direct way is to convert your dates to the ISO8601 yyyy-mm-ddThh:mm:ss. sss date format and use the writedatetime() worksheet method: See the writedatetime() section of the documentation for more details. A general methodology for handling date strings with writedatetime() is: Here is an example: For a slightly more advanced solution you can modify the write() method to handle date formats of your choice via the addwritehandler() method. See the addwritehandler() section of the docs and the writehandler3.pl and writehandler4.pl programs in the examples directory of the distro. The writedatetime() method above is just one way of handling dates and times. You can also use the convertdatetime() worksheet method to convert from an ISO8601 style date string to an Excel date and time number. The Excel::Writer::XLSX::Utility module which is included in the distro has datetime handling functions: Note: some of these functions require additional CPAN modules. Excel allows you to group rows or columns so that they can be hidden or displayed with a single mouse click. This feature is referred to as outlines. Outlines can reduce complex data down to a few salient sub-totals or summaries. This feature is best viewed in Excel but the following is an ASCII representation of what a worksheet with three outlines might look like. Rows 3-4 and rows 7-8 are grouped at level 2. Rows 2-9 are grouped at level 1. The lines at the left hand side are called outline level bars. Clicking the minus sign on each of the level 2 outlines will collapse and hide the data as shown in the next figure. The minus sign changes to a plus sign to indicate that the data in the outline is hidden. Clicking on the minus sign on the level 1 outline will collapse the remaining rows as follows: Grouping in Excel::Writer::XLSX is achieved by setting the outline level via the setrow() and setcolumn() worksheet methods: The following example sets an outline level of 1 for rows 1 and 2 (zero-indexed) and columns B to G. The parameters height and XF are assigned default values since they are undefined: Excel allows up to 7 outline levels. Therefore the level parameter should be in the range 0 60 level 60 7 . Rows and columns can be collapsed by setting the hidden flag for the hidden rowscolumns and setting the collapsed flag for the rowcolumn that has the collapsed symbol: Note: Setting the collapsed flag is particularly important for compatibility with OpenOffice. org and Gnumeric. For a more complete example see the outline. pl and outlinecollapsed. pl programs in the examples directory of the distro. Some additional outline properties can be set via the outlinesettings() worksheet method, see above. Data validation is a feature of Excel which allows you to restrict the data that a users enters in a cell and to display help and warning messages. It also allows you to restrict input to values in a drop down list. A typical use case might be to restrict data in a cell to integer values in a certain range, to provide a help message to indicate the required value and to issue a warning if the input data doesn39t meet the stated criteria. In Excel::Writer::XLSX we could do that as follows: For more information on data validation see the following Microsoft support article 34Description and examples of data validation in Excel34: support. microsoftkb211485 . The following sections describe how to use the datavalidation() method and its various options. datavalidation( row, col, ) The datavalidation() method is used to construct an Excel data validation. It can be applied to a single cell or a range of cells. You can pass 3 parameters such as (row, col, ) or 5 parameters such as (firstrow, firstcol, lastrow, lastcol, ). You can also use A1 style notation. For example: See also the note about 34Cell notation34 for more information. The last parameter in datavalidation() must be a hash ref containing the parameters that describe the type and style of the data validation. The allowable parameters are: These parameters are explained in the following sections. Most of the parameters are optional, however, you will generally require the three main options validate. criteria and value . The datavalidation method returns: This parameter is passed in a hash ref to datavalidation() . The validate parameter is used to set the type of data that you wish to validate. It is always required and it has no default value. Allowable values are: any is used to specify that the type of data is unrestricted. This is useful to display an input message without restricting the data that can be entered. integer restricts the cell to integer values. Excel refers to this as 39whole number39. decimal restricts the cell to decimal values. list restricts the cell to a set of user specified values. These can be passed in an array ref or as a cell range (named ranges aren39t currently supported): Excel requires that range references are only to cells on the same worksheet. date restricts the cell to date values. Dates in Excel are expressed as integer values but you can also pass an ISO8601 style string as used in writedatetime(). See also 34DATES AND TIME IN EXCEL34 for more information about working with Excel39s dates. time restricts the cell to time values. Times in Excel are expressed as decimal values but you can also pass an ISO8601 style string as used in writedatetime(). See also 34DATES AND TIME IN EXCEL34 for more information about working with Excel39s times. length restricts the cell data based on an integer string length. Excel refers to this as 39Text length39. custom restricts the cell based on an external Excel formula that returns a TRUEFALSE value. This parameter is passed in a hash ref to datavalidation() . The criteria parameter is used to set the criteria by which the data in the cell is validated. It is almost always required except for the list and custom validate options. It has no default value. Allowable values are: You can either use Excel39s textual description strings, in the first column above, or the more common symbolic alternatives. The following are equivalent: The list and custom validate options don39t require a criteria. If you specify one it will be ignored. This parameter is passed in a hash ref to datavalidation() . The value parameter is used to set the limiting value to which the criteria is applied. It is always required and it has no default value. You can also use the synonyms minimum or source to make the validation a little clearer and closer to Excel39s description of the parameter: This parameter is passed in a hash ref to datavalidation() . The maximum parameter is used to set the upper limiting value when the criteria is either 39between39 or 39not between39 : This parameter is passed in a hash ref to datavalidation() . The ignoreblank parameter is used to toggle on and off the 39Ignore blank39 option in the Excel data validation dialog. When the option is on the data validation is not applied to blank data in the cell. It is on by default. This parameter is passed in a hash ref to datavalidation() . The dropdown parameter is used to toggle on and off the 39In-cell dropdown39 option in the Excel data validation dialog. When the option is on a dropdown list will be shown for list validations. It is on by default. This parameter is passed in a hash ref to datavalidation() . The inputtitle parameter is used to set the title of the input message that is displayed when a cell is entered. It has no default value and is only displayed if the input message is displayed. See the inputmessage parameter below. The maximum title length is 32 characters. This parameter is passed in a hash ref to datavalidation() . The inputmessage parameter is used to set the input message that is displayed when a cell is entered. It has no default value. The message can be split over several lines using newlines, 34n34 in double quoted strings. The maximum message length is 255 characters. This parameter is passed in a hash ref to datavalidation() . The showinput parameter is used to toggle on and off the 39Show input message when cell is selected39 option in the Excel data validation dialog. When the option is off an input message is not displayed even if it has been set using inputmessage. It is on by default. This parameter is passed in a hash ref to datavalidation() . The errortitle parameter is used to set the title of the error message that is displayed when the data validation criteria is not met. The default error title is 39Microsoft Excel39. The maximum title length is 32 characters. This parameter is passed in a hash ref to datavalidation() . The errormessage parameter is used to set the error message that is displayed when a cell is entered. The default error message is 34The value you entered is not valid. nA user has restricted values that can be entered into the cell.34. The message can be split over several lines using newlines, 34n34 in double quoted strings. The maximum message length is 255 characters. This parameter is passed in a hash ref to datavalidation() . The errortype parameter is used to specify the type of error dialog that is displayed. There are 3 options: The default is 39stop39 . This parameter is passed in a hash ref to datavalidation() . The showerror parameter is used to toggle on and off the 39Show error alert after invalid data is entered39 option in the Excel data validation dialog. When the option is off an error message is not displayed even if it has been set using errormessage. It is on by default. Example 1. Limiting input to an integer greater than a fixed value. Example 2. Limiting input to an integer greater than a fixed value where the value is referenced from a cell. Example 3. Limiting input to a decimal in a fixed range. Example 4. Limiting input to a value in a dropdown list. Example 5. Limiting input to a value in a dropdown list where the list is specified as a cell range. Example 6. Limiting input to a date in a fixed range. Example 7. Displaying a message when the cell is selected. See also the datavalidate. pl program in the examples directory of the distro. Conditional formatting is a feature of Excel which allows you to apply a format to a cell or a range of cells based on a certain criteria. For example the following criteria is used to highlight cells 62 50 in red in the conditionalformat. pl example from the distro: conditionalformatting( row, col, ) The conditionalformatting() method is used to apply formatting based on user defined criteria to an Excel::Writer::XLSX file. It can be applied to a single cell or a range of cells. You can pass 3 parameters such as (row, col, ) or 5 parameters such as (firstrow, firstcol, lastrow, lastcol, ). You can also use A1 style notation. For example: See also the note about 34Cell notation34 for more information. Using A1 style notation is also possible to specify non-contiguous ranges, separated by a comma. For example: The last parameter in conditionalformatting() must be a hash ref containing the parameters that describe the type and style of the data validation. The main parameters are: Other, less commonly used parameters are: Additional parameters which are used for specific conditional format types are shown in the relevant sections below. This parameter is passed in a hash ref to conditionalformatting() . The type parameter is used to set the type of conditional formatting that you wish to apply. It is always required and it has no default value. Allowable type values and their associated parameters are: All conditional formatting types have a format parameter, see below. Other types and parameters such as icon sets will be added in time. This is the most common conditional formatting type. It is used when a format is applied to a cell based on a simple criterion. For example: Or, using the between criteria: The criteria parameter is used to set the criteria by which the cell data will be evaluated. It has no default value. The most common criteria as applied to are: You can either use Excel39s textual description strings, in the first column above, or the more common symbolic alternatives. Additional criteria which are specific to other conditional format types are shown in the relevant sections below. The value is generally used along with the criteria parameter to set the rule by which the cell data will be evaluated. The value property can also be an cell reference. The format parameter is used to specify the format that will be applied to the cell when the conditional formatting criterion is met. The format is created using the addformat() method in the same way as cell formats: The conditional format follows the same rules as in Excel: it is superimposed over the existing cell format and not all font and border properties can be modified. Font properties that can39t be modified are font name, font size, superscript and subscript. The border property that cannot be modified is diagonal borders. Excel specifies some default formats to be used with conditional formatting. You can replicate them using the following Excel::Writer::XLSX formats: The minimum parameter is used to set the lower limiting value when the criteria is either 39between39 or 39not between39 : The maximum parameter is used to set the upper limiting value when the criteria is either 39between39 or 39not between39. See the previous example. The date type is the same as the cell type and uses the same criteria and values. However it allows the value. minimum and maximum properties to be specified in the ISO8601 yyyy-mm-ddThh:mm:ss. sss date format which is detailed in the writedatetime() method. The timeperiod type is used to specify Excel39s 34Dates Occurring34 style conditional format. The period is set in the criteria and can have one of the following values: The text type is used to specify Excel39s 34Specific Text34 style conditional format. It is used to do simple string matching using the criteria and value parameters: The criteria can have one of the following values: The value parameter should be a string or single character. The average type is used to specify Excel39s 34Average34 style conditional format. The type of average for the conditional format range is specified by the criteria : The duplicate type is used to highlight duplicate cells in a range: The unique type is used to highlight unique cells in a range: The top type is used to specify the top n values by number or percentage in a range: The criteria can be used to indicate that a percentage condition is required: The bottom type is used to specify the bottom n values by number or percentage in a range. It takes the same parameters as top. see above. The blanks type is used to highlight blank cells in a range: The noblanks type is used to highlight non blank cells in a range: The errors type is used to highlight error cells in a range: The noerrors type is used to highlight non error cells in a range: The 2colorscale type is used to specify Excel39s 342 Color Scale34 style conditional format. This conditional type can be modified with mintype. maxtype. minvalue. maxvalue. mincolor and maxcolor. see below. The 3colorscale type is used to specify Excel39s 343 Color Scale34 style conditional format. This conditional type can be modified with mintype. midtype. maxtype. minvalue. midvalue. maxvalue. mincolor. midcolor and maxcolor. see below. The databar type is used to specify Excel39s 34Data Bar34 style conditional format. This conditional type can be modified with mintype. maxtype. minvalue. maxvalue and barcolor. see below. The formula type is used to specify a conditional format based on a user defined formula: The formula is specified in the criteria . The mintype and maxtype properties are available when the conditional formatting type is 2colorscale. 3colorscale or databar. The midtype is available for 3colorscale. The properties are used as follows: The available minmidmax types are: The minvalue and maxvalue properties are available when the conditional formatting type is 2colorscale. 3colorscale or databar. The midvalue is available for 3colorscale. The properties are used as follows: The mincolor and maxcolor properties are available when the conditional formatting type is 2colorscale. 3colorscale or databar. The midcolor is available for 3colorscale. The properties are used as follows: The color can be specifies as an Excel::Writer::XLSX color index or, more usefully, as a HTML style RGB hex number, as shown above. The stopiftrue parameter, if set to a true value, will enable the 34stop if true34 feature on the conditional formatting rule, so that subsequent rules are not examined for any cell on which the conditions for this rule are met. Example 1. Highlight cells greater than an integer value. Example 2. Highlight cells greater than a value in a reference cell. Example 3. Highlight cells greater than a certain date: Example 4. Highlight cells with a date in the last seven days: Example 5. Highlight cells with strings starting with the letter b : Example 6. Highlight cells that are 1 std deviation above the average for the range: Example 7. Highlight duplicate cells in a range: Example 8. Highlight unique cells in a range. Example 9. Highlight the top 10 cells. Example 10. Highlight blank cells. See also the conditionalformat. pl example program in EXAMPLES . Sparklines are a feature of Excel 2010 which allows you to add small charts to worksheet cells. These are useful for showing visual trends in data in a compact format. In Excel::Writer::XLSX Sparklines can be added to cells using the addsparkline() worksheet method: Note: Sparklines are a feature of Excel 2010 only. You can write them to an XLSX file that can be read by Excel 2007 but they won39t be displayed. addsparkline( ) The addsparkline() worksheet method is used to add sparklines to a cell or a range of cells. The parameters to addsparkline() must be passed in a hash ref. The main sparkline parameters are: Other, less commonly used parameters are: These parameters are explained in the sections below: This is the cell where the sparkline will be displayed: The location should be a single cell. (For multiple cells see 34Grouped Sparklines34 below). To specify the location in row-column notation use the xlrowcoltocell() function from the Excel::Writer::XLSX::Utility module. This specifies the cell data range that the sparkline will plot: The range should be a 2D array. (For 3D arrays of cells see 34Grouped Sparklines34 below). If range is not on the same worksheet you can specify its location using the usual Excel notation: If the worksheet contains spaces or special characters you should quote the worksheet name in the same way that Excel does: To specify the location in row-column notation use the xlrange() or xlrangeformula() functions from the Excel::Writer::XLSX::Utility module. Specifies the type of sparkline. There are 3 available sparkline types: Excel provides 36 built-in Sparkline styles in 6 groups of 6. The style parameter can be used to replicate these and should be a corresponding number from 1. 36. The style number starts in the top left of the style grid and runs left to right. The default style is 1. It is possible to override colour elements of the sparklines using the color parameters below. Turn on the markers for line style sparklines. Markers aren39t shown in Excel for column and winloss sparklines. Highlight negative values in a sparkline range. This is usually required with winloss sparklines. Display a horizontal axis in the sparkline: Plot the data from right-to-left instead of the default left-to-right: Adjust the default line weight (thickness) for line style sparklines. The weight value should be one of the following values allowed by Excel: Highlight points in a sparkline range. Specify the maximum and minimum vertical axis values: As a special case you can set the maximum and minimum to be for a group of sparklines rather than one: Define how empty cells are handled in a sparkline. The available options are: Plot data in hidden rows and columns: Note, this option is off by default. Specify an alternative date axis for the sparkline. This is useful if the data being plotted isn39t at fixed width intervals: The number of cells in the date range should correspond to the number of cells in the data range. It is possible to override the colour of a sparkline style using the following parameters: The color should be specified as a HTML style rrggbb hex value: The addsparkline() worksheet method can be used multiple times to write as many sparklines as are required in a worksheet. However, it is sometimes necessary to group contiguous sparklines so that changes that are applied to one are applied to all. In Excel this is achieved by selecting a 3D range of cells for the data range and a 2D range of cells for the location . In Excel::Writer::XLSX, you can simulate this by passing an array refs of values to location and range : See the sparklines1.pl and sparklines2.pl example programs in the examples directory of the distro. Tables in Excel are a way of grouping a range of cells into a single entity that has common formatting or that can be referenced from formulas. Tables can have column headers, autofilters, total rows, column formulas and default formatting. Note, tables don39t work in Excel::Writer::XLSX when setoptimization() mode in on. addtable( row1, col1, row2, col2, ) Tables are added to a worksheet using the addtable() method: The data range can be specified in 39A139 or 39rowcol39 notation (see also the note about 34Cell notation34 for more information): The last parameter in addtable() should be a hash ref containing the parameters that describe the table options and data. The available parameters are: The table parameters are detailed below. There are no required parameters and the hash ref isn39t required if no options are specified. The data parameter can be used to specify the data in the cells of the table. Table data can also be written separately, as an array or individual cells. Writing the cell data separately is occasionally required when you need to control the write() method used to populate the cells or if you wish to tweak the cell formatting. The data structure should be an array ref of array refs holding row data as shown above. The headerrow parameter can be used to turn on or off the header row in the table. It is on by default. The header row will contain default captions such as Column 1. Column 2. etc. These captions can be overridden using the columns parameter below. The autofilter parameter can be used to turn on or off the autofilter in the header row. It is on by default. The autofilter is only shown if the headerrow is on. Filters within the table are not supported. The bandedrows parameter can be used to used to create rows of alternating colour in the table. It is on by default. The bandedcolumns parameter can be used to used to create columns of alternating colour in the table. It is off by default. The firstcolumn parameter can be used to highlight the first column of the table. The type of highlighting will depend on the style of the table. It may be bold text or a different colour. It is off by default. The lastcolumn parameter can be used to highlight the last column of the table. The type of highlighting will depend on the style of the table. It may be bold text or a different colour. It is off by default. The style parameter can be used to set the style of the table. Standard Excel table format names should be used (with matching capitalisation): The default table style is 39Table Style Medium 939. By default tables are named Table1. Table2. etc. The name parameter can be used to set the name of the table: If you override the table name you must ensure that it doesn39t clash with an existing table name and that it follows Excel39s requirements for table names office. microsoften-001excel-helpdefine-and-use-names-in-formulas-HA010147120.aspxBMsyntaxrulesfornames . If you need to know the name of the table, for example to use it in a formula, you can get it as follows: The totalrow parameter can be used to turn on the total row in the last row of a table. It is distinguished from the other rows by a different formatting and also with dropdown SUBTOTAL functions. The default total row doesn39t have any captions or functions. These must by specified via the columns parameter below. The columns parameter can be used to set properties for columns within the table. The sub-properties that can be set are: The column data must be specified as an array ref of hash refs. For example to override the default 39Column n39 style table headers: If you don39t wish to specify properties for a specific column you pass an empty hash ref and the defaults will be applied: Column formulas can by applied using the formula column property: The Excel 2007 This Row and Excel 2010 structural references are supported within the formula. As stated above the totalrow table parameter turns on the 34Total34 row in the table but it doesn39t populate it with any defaults. Total captions and functions must be specified via the columns property and the totalstring. totalfunction and totalvalue sub properties: The supported totals row SUBTOTAL functions are: User defined functions or formulas aren39t supported. It is also possible to set a calculated value for the totalfunction using the totalvalue sub property. This is only necessary when creating workbooks for applications that cannot calculate the value of formulas automatically. This is similar to setting the value optional property in writeformula() : Formatting can also be applied to columns, to the column data using format and to the header using headerformat : Standard Excel::Writer::XLSX format objects can be used. However, they should be limited to numerical formats for the columns and simple formatting like text wrap for the headers. Overriding other table formatting may produce inconsistent results. The following is a brief introduction to formulas and functions in Excel and Excel::Writer::XLSX. A formula is a string that begins with an equals sign: The formula can contain numbers, strings, boolean values, cell references, cell ranges and functions. Named ranges are not supported. Formulas should be written as they appear in Excel, that is cells and functions must be in uppercase. Cells in Excel are referenced using the A1 notation system where the column is designated by a letter and the row by a number. Columns range from A to XFD i. e. 0 to 16384, rows range from 1 to 1048576. The Excel::Writer::XLSX::Utility module that is included in the distro contains helper functions for dealing with A1 notation, for example: The Excel notation in cell references is also supported. This allows you to specify whether a row or column is relative or absolute. This only has an effect if the cell is copied. The following examples show relative and absolute values. Formulas can also refer to cells in other worksheets of the current workbook. For example: The sheet reference and the cell reference are separated by. the exclamation mark symbol. If worksheet names contain spaces, commas or parentheses then Excel requires that the name is enclosed in single quotes as shown in the last two examples above. In order to avoid using a lot of escape characters you can use the quote operator q to protect the quotes. See perlop in the main Perl documentation. Only valid sheet names that have been added using the addworksheet() method can be used in formulas. You cannot reference external workbooks. The following table lists the operators that are available in Excel39s formulas. The majority of the operators are the same as Perl39s, differences are indicated: The range and comma operators can have different symbols in non-English versions of Excel, see below. For a general introduction to Excel39s formulas and an explanation of the syntax of the function refer to the Excel help files or the following: office. microsoften-usassistanceCH062528031033.aspx . In most cases a formula in Excel can be used directly in the writeformula method. However, there are a few potential issues and differences that the user should be aware of. These are explained in the following sections. Excel stores formulas in the format of the US English version, regardless of the language or locale of the end-user39s version of Excel. Therefore all formula function names written using Excel::Writer::XLSX must be in English: Also, formulas must be written with the US style separatorrange operator which is a comma (not semi-colon). Therefore a formula with multiple values should be written as follows: If you have a non-English version of Excel you can use the following multi-lingual Formula Translator (en. excel-translator. delanguage ) to help you convert the formula. It can also replace semi-colons with commas. Excel 2010 and later added functions which weren39t defined in the original file specification. These functions are referred to by Microsoft as future functions. Examples of these functions are ACOT. CHISQ. DIST. RT. CONFIDENCE. NORM. STDEV. P. STDEV. S and WORKDAY. INTL . When written using writeformula() these functions need to be fully qualified with a xlfn. (or other) prefix as they are shown the list below. For example: They will appear without the prefix in Excel. The following list is taken from the MS XLSX extensions documentation on future functions: msdn. microsoften-uslibrarydd90748028voffice.1229.aspx : Worksheet tables can be added with Excel::Writer::XLSX using the addtable() method: By default tables are named Table1. Table2. etc. in the order that they are added. However it can also be set by the user using the name parameter: If you need to know the name of the table, for example to use it in a formula, you can get it as follows: When used in a formula a table name such as TableX should be referred to as TableX (like a Perl array): If there is an error in the syntax of a formula it is usually displayed in Excel as NAME. If you encounter an error like this you can debug it as follows: Finally if you have completed all the previous steps and still get a NAME error you can examine a valid Excel file to see what the correct syntax should be. To do this you should create a valid formula in Excel and save the file. You can then examine the XML in the unzipped file. The following shows how to do that using Linux unzip and libxml39s xmllint xmlsoft. orgxmllint. html to format the XML for clarity: Excel::Writer::XLSX doesn39t calculate the result of a formula and instead stores the value 0 as the formula result. It then sets a global flag in the XLSX file to say that all formulas and functions should be recalculated when the file is opened. This is the method recommended in the Excel documentation and in general it works fine with spreadsheet applications. However, applications that don39t have a facility to calculate formulas will only display the 0 results. Examples of such applications are Excel Viewer, PDF Converters, and some mobile device applications. If required, it is also possible to specify the calculated result of the formula using the optional last value parameter in writeformula : The value parameter can be a number, a string, a boolean sting ( 39TRUE39 or 39FALSE39 ) or one of the following Excel error codes: It is also possible to specify the calculated result of an array formula created with writearrayformula : However, using this parameter only writes a single value to the upper left cell in the result array. For a multi-cell array formula where the results are required, the other result values can be specified by using writenumber() to write to the appropriate cell: An Excel xlsm file is exactly the same as a xlsx file except that is includes an additional vbaProject. bin file which contains functions andor macros. Excel uses a different extension to differentiate between the two file formats since files containing macros are usually subject to additional security checks. The vbaProject. bin file is a binary OLE COM container. This was the format used in older xls versions of Excel prior to Excel 2007. Unlike all of the other components of an xlsxxlsm file the data isn39t stored in XML format. Instead the functions and macros as stored as pre-parsed binary format. As such it wouldn39t be feasible to define macros and create a vbaProject. bin file from scratch (at least not in the remaining lifespan and interest levels of the author). Instead a workaround is used to extract vbaProject. bin files from existing xlsm files and then add these to Excel::Writer::XLSX files. The extractvba utility is used to extract the vbaProject. bin binary from an Excel 2007 xlsm file. The utility is included in the Excel::Writer::XLSX bin directory and is also installed as a standalone executable file: Once the vbaProject. bin file has been extracted it can be added to the Excel::Writer::XLSX workbook using the addvbaproject() method: If the VBA file contains functions you can then refer to them in calculations using writeformula : Excel files that contain functions and macros should use an xlsm extension or else Excel will complain and possibly not open the file: It is also possible to assign a macro to a button that is inserted into a worksheet using the insertbutton() method: It may be necessary to specify a more explicit macro name prefixed by the workbook VBA name as follows: See the macros. pl from the examples directory for a working example. Note: Button is the only VBA Control supported by Excel::Writer::XLSX. Due to the large effort in implementation (1 man months) it is unlikely that any other form elements will be added in the future. VBA macros generally refer to workbook and worksheet objects. If the VBA codenames aren39t specified then Excel::Writer::XLSX will use the Excel defaults of ThisWorkbook and Sheet1. Sheet2 etc. If the macro uses other codenames you can set them using the workbook and worksheet setvbaname() methods as follows: You can find the names that are used in the VBA editor or by unzipping the xlsm file and grepping the files. The following shows how to do that using libxml39s xmllint xmlsoft. orgxmllint. html to format the XML for clarity: Note: This step is particularly important for macros created with non-English versions of Excel. This feature should be considered experimental and there is no guarantee that it will work in all cases. Some effort may be required and some knowledge of VBA will certainly help. If things don39t work out here are some things to try: Start with a simple macro file, ensure that it works and then add complexity. Try to extract the macros from an Excel 2007 file. The method should work with macros from later versions (it was also tested with Excel 2010 macros). However there may be features in the macro files of more recent version of Excel that aren39t backward compatible. Check the code names that macros use to refer to the workbook and worksheets (see the previous section above). In general VBA uses a code name of ThisWorkbook to refer to the current workbook and the sheet name (such as Sheet1 ) to refer to the worksheets. These are the defaults used by Excel::Writer::XLSX. If the macro uses other names then you can specify these using the workbook and worksheet setvbaname() methods: The following example shows some of the basic features of Excel::Writer::XLSX. The following is a general example which demonstrates some features of working with multiple worksheets. Example of how to add conditional formatting to an Excel::Writer::XLSX file. The example below highlights cells that have a value greater than or equal to 50 in red and cells below that value in green. The following is a simple example of using functions. The following example converts a tab separated file called tab. txt into an Excel file called tab. xlsx . NOTE: This is a simple conversion program for illustrative purposes only. For converting a CSV or Tab separated or any other type of delimited text file to Excel I recommend the more rigorous csv2xls program that is part of H. Merijn Brand39s Text::CSVXS module distro. See the examplescsv2xls link here: search. cpan. org The following is a description of the example files that are provided in the standard Excel::Writer::XLSX distribution. They demonstrate the different features and options of the module. See Excel::Writer::XLSX::Examples for more details. The following limits are imposed by Excel 2007: Per worksheet. Excel allows a greater number of non-unique hyperlinks if they are contiguous and can be grouped into a single range. This will be supported in a later version of Excel::Writer::XLSX if possible. The Excel::Writer::XLSX module is a drop-in replacement for Spreadsheet::WriteExcel . It supports all of the features of Spreadsheet::WriteExcel with some minor differences noted below. Spreadsheet::WriteExcel was written to optimise speed and reduce memory usage. However, these design goals meant that it wasn39t easy to implement features that many users requested such as writing formatting and data separately. As a result Excel::Writer::XLSX takes a different design approach and holds a lot more data in memory so that it is functionally more flexible. The effect of this is that Excel::Writer::XLSX is about 30 slower than Spreadsheet::WriteExcel and uses 5 times more memory. In addition the extended row and column ranges in Excel 2007 mean that it is possible to run out of memory creating large files. This was almost never an issue with Spreadsheet::WriteExcel. This memory usage can be reduced almost completely by using the Workbook setoptimization() method: This also gives an increase in performance to within 1-10 of Spreadsheet::WriteExcel, see below. The trade-off is that you won39t be able to take advantage of any new features that manipulate cell data after it is written. One such feature is Tables. The performance figures below show execution speed and memory usage for 60 columns x N rows for a 5050 mixture of strings and numbers. Percentage speeds are relative to Spreadsheet::WriteExcel. The module can be installed using the standard Perl procedure: A filename must be given in the constructor. The file cannot be opened for writing. The directory that you are writing to may be protected or the file may be in use by another program. On Windows this is usually caused by the file that you are trying to create clashing with a version that is already open and locked by Excel. This warning occurs when you create an XLSX file but give it an xls extension. Depending on your requirements, background and general sensibilities you may prefer one of the following methods of getting data into Excel: This module is the precursor to Excel::Writer::XLSX and uses the same interface. It produces files in the Excel Biff xls format that was used in Excel versions 97-2003. These files can still be read by Excel 2007 but have some limitations in relation to the number of rows and columns that the format supports. Win32::OLE module and office automationThis requires a Windows platform and an installed copy of Excel. This is the most powerful and complete method for interfacing with Excel. CSV, comma separated variables or textExcel will open and automatically convert files with a csv extension. To create CSV files refer to the Text::CSVXS module. DBI with DBD::ADO or DBD::ODBCExcel files contain an internal index table that allows them to act like a database file. Using one of the standard Perl database modules you can connect to an Excel file as a database. To read data from Excel files try: A module for reading formatted or unformatted data form XLSX files. A lightweight module for reading data from XLSX files. This module can read data from an Excel XLS file but it doesn39t support the XLSX format. Win32::OLE module and office automation (reading)DBI with DBD::ADO or DBD::ODBC. Memory usage is very high for large worksheets. If you run out of memory creating large worksheets use the setoptimization() method. See 34SPEED AND MEMORY USAGE34 for more information. Perl packaging programs can39t find chart modules. When using Excel::Writer::XLSX charts with Perl packagers such as PAR or Cava you should explicitly include the chart that you are trying to create in your use statements. This isn39t a bug as such but it might help someone from banging their head off a wall: If you wish to submit a bug report run the bugreport. pl program in the examples directory of the distro. The roadmap is as follows: New separated dataformatting API to allow cells to be formatted after data is added. More charting features. There is a Google group for discussing and asking questions about Excel::Writer::XLSX. This is a good place to search to see if your question has been asked before: groups. googlegroupspreadsheet-writeexcel . If you39d care to donate to the Excel::Writer::XLSX project or sponsor a new feature, you can do so via PayPal: tinyurl7ayes . The following people contributed to the debugging, testing or enhancement of Excel::Writer::XLSX: Rob Messer of IntelliSurvey gave me the initial prompt to port Spreadsheet::WriteExcel to the XLSX format. IntelliSurvey (intellisurvey ) also sponsored large files optimisations and the charting feature. Bariatric Advantage (bariatricadvantage ) sponsored work on chart formatting. Eric Johnson provided the ability to use secondary axes with charts. Thanks to Foxtons (foxtons. co. uk ) for sponsoring this work. BuildFax (buildfax ) sponsored the Tables feature and the Chart point formatting feature. Because this software is licensed free of charge, there is no warranty for the software, to the extent permitted by applicable law. Except when otherwise stated in writing the copyright holders andor other parties provide the software 34as is34 without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The entire risk as to the quality and performance of the software is with you. Should the software prove defective, you assume the cost of all necessary servicing, repair, or correction. In no event unless required by applicable law or agreed to in writing will any copyright holder, or any other party who may modify andor redistribute the software as permitted by the above licence, be liable to you for damages, including any general, special, incidental, or consequential damages arising out of the use or inability to use the software (including but not limited to loss of data or data being rendered inaccurate or losses sustained by you or third parties or a failure of the software to operate with any other software), even if such holder or other party has been advised of the possibility of such damages. John McNamara jmcnamaracpan. org