Criando planilhas Excel Usando Outros Ambientes


Artigo de Simon St.Laurent (livremente traduzido por André Bernardes)
Apesar do MS Excel e outros aplicativos de planilhas eletrônicas terem as suas próprias interfaces gráficas para criação e leitura das suas respectivas planilhas, algumas vezes necessitamos criar arquivos com a extensão .XLS diretamente através de outros programas.

Quer criemos arquivos MS Excel a partir de um Bancos de Dados em um servidor Apache ou queiramos mostrar infomações guardadas em um programa Java para usuários do MS Excel, para ambas as situações existirão uma variedade de pacotes que nos habilitarão a criar e acessar os arquivos .XLS. Mesmo estes aplicativos sendo freqüentemente mais difícieis de utilizar do que uma “SpreadsheetML”. Estes geralmente reproduzem arquivos legíveis para qualquer versão do MS Excel, desde a versão 97 (Incluindo-se aí a versão para o Macintosh), e muitas vezes têm suporte razoável para as características básicas da interface original do MS Excel.

Alguns dos mais populares (e gratuitos) pacotes para se trabalhar com dados do MS Excel, são: Spreadsheet:: WriteExcel Um pacote Perl para a criação de documentos MS Excel, está disponível em: http://search.cpan.org/dist/Spreadsheet-WriteExcel/ Spreadsheet::ParseExcel Uma ferramente que ativa programas desenvolvidos com o Perl e lê arquivos MS Excel, está disponível em: http://search.cpan.org/~kwitknr/Spreadsheet-ParseExcel-0.2602/ Jakarta POI Um produto da Apache Project que propicia a leitura e gravação nas planilhas MS Excel através de uma API Java, está disponível em: http://jakarta.apache.org/poi/index.html JExcelApi Uma API Java para leitura e escrita de planilhas do MS Excel, incluindo a característica adicional de efetuar conversões MS Excel-para-CSV e MS Excel-para-XML, está disponível em: http://www.andykhan.com/jexcelapi/

Você também pode automatizar o Excel de diversos outros modos. Poderá fazê-lo através do Microsoft's .NET Framework. Um exemplo de como fazê-lo com o C# encontra-se http://www.eggheadcafe.com/articles/20021012.asp.

Um outro exemplo de como processar este trabalho é através de um código em Java, o qual criará uma planilha utilizando o POI API. (Se você não for um programador Java, possivelmente não faz a menor idéia do que estou falando): 


Exemplo: Código Java de geração de uma planilha eletrônica com o POI


// This code is derived from the org.apache.poi.hssf.dev.HSSF class, // 
hence the long license. 
/* ==================================================================== * 
The Apache Software License, Version 1.1 
* Copyright (c) 2003 The Apache Software Foundation. All rights * reserved. 
* Redistribution and use in source and binary forms, with or without * 
modification, are permitted provided that the following conditions * are met: 
* * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. 
* * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. 
* * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. 
* * 4. The names "Apache" and "Apache Software Foundation" and * "Apache POI" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact apache@apache.org. 
* * 5. Products derived from this software may not be called "Apache", * "Apache POI", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. 


* * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. 
* ==================================================================== * * 


This software consists of voluntary contributions made by many 
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see *
*/ import java.io.*; import java.util.Random; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.hssf.record.*; import org.apache.poi.hssf.model.
*; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.*; public class PoiDemo { public static void main (String[] args) throws Exception { short rownum; // create a destination file FileOutputStream out = new FileOutputStream("zingot.xls"); // create a new workbook object; note that the workbook // and the file are two separate things until the very // end, when the workbook is written to the file. HSSFWorkbook wb = new HSSFWorkbook( ); // create a new worksheet HSSFSheet ws = wb.createSheet( ); // create a row object reference for later use HSSFRow r = null; // create a cell object reference HSSFCell c = null; // create two cell styles - formats //need to be defined before they are used HSSFCellStyle cs1 = wb.createCellStyle( ); HSSFCellStyle cs2 = wb.createCellStyle( ); HSSFDataFormat df = wb.createDataFormat( ); // create two font objects for formatting HSSFFont f1 = wb.createFont( ); HSSFFont f2 = wb.createFont( ); //set font 1 to 10 point bold type f1.setFontHeightInPoints((short) 10); f1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //set font 2 to 10 point red type f2.setFontHeightInPoints((short) 10); f2.setColor( (short)HSSFFont.COLOR_RED ); //for cell style 1, use font 1 and set data format cs1.setFont(f1); cs1.setDataFormat(df.getFormat("#,##0.0")); //for cell style 2, use font 2, set a thin border, text format cs2.setBorderBottom(cs2.BORDER_THIN); cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("text")); cs2.setFont(f2); // set the sheet name in Unicode wb.setSheetName(0, "Test sheet", HSSFWorkbook.ENCODING_UTF_16 ); // create a sheet with 10 rows (0-9) for (rownum = (short) 0; rownum < r =" ws.createRow(rownum);" cellnum =" (short)" c =" r.createCell(cellnum);" c =" r.createCell((short)" r =" ws.createRow(rownum);" cellnum =" (short)" column=" 65+cellnum;" columnlabel="(char)column;" formula="SUM(" c =" r.createCell(cellnum);">


Para executar este código, primeiramente precisa baixar a última versão do arquivo binário POI e colocá-lo como arquivo jar (poi-2.0-final-20040126.jar neste caso) no seu classpath, de acordo coma plataforma na qual você deseja rodar. Quando executá-lo, serão criados arquivos simples, chamados de zingot.xls. Ao abrir estes arquivos verá algo similar ao mostrado mais abaixo: Planilhas criadas a partir do programa em Java (Ambiente Windows): Planilhas criadas a partir do programa em Java (Ambiente Macintosh) A lógica mostrada acima é um raro e exemplar modelo de como criar uma planilha, mas esta apenas mostra as funcionalidades básicas para criar planilhas, células e fórmulas. Se você usar este modelo para construir as suas próprias planilhas, indubitavelmente adicionará outras características.

Outra característica do POI é particularmente inerentemente voltada para produzir resultados para a web de modo dinâmico. Pode combinar as características POI com Cocoon, um framework Java também da Apache, que usa documentos XML além de outras fontes que geram conteúdo acessível pela web através dos browsers. Em XML.com encontrará um artigo interessante http://www.xml.com/pub/a/2003/01/22/cocoon-excel.html com detalhes demonstrando como fazer isso.

Perfil - André Luiz Bernardes


André Luiz Bernardes





Busca a constante atualização tecnológica, aprecia boa leitura, música, ciências, economia e internet


Procura aprofundar-se nos processos da empresa, não restringindo-se ao departamento.

Desenvoltura para falar em público, seja em treinamentos, palestras, exposições, demonstrações ou workshops.

Demonstra facilidade em compartilhar conhecimento. 



Tags: André Luiz Bernardes, VBA, Office, Microsoft, developer, desenvolvedor, MOS, Microsoft Office Solution Provide, Microsoft Office Specialist




diHITT - Notícias