1. Introdução
Os relatórios geralmente estão envolvidos no desenvolvimento da Web Java. Em projetos recentes, precisamos exibir os dados no banco de dados como uma tabela e exportá -los como um arquivo do Excel.
2 Pacotes JAR relacionados
O uso do POI pode resolver os problemas de importação e exportação do Excel. Endereço de download de POI:
POI-3.6-20091214.Jar
3. Código da chave
Primeiro importe o pacote de jar acima.
Ao gerar o Excel, o formulário geral da fonte de dados é uma lista. A seguir, o código que gera formato Excel:
/ *** A seguir, é apresentada a geração de operação do Excel*/ // 1. Crie uma pasta de trabalho, correspondente a um arquivo do Excel, HSSFWorkbook WB = novo HSSFWorkbook (); // 2. Adicione uma folha na pasta de trabalho, correspondendo a uma folha no Excel HSSFSheet Sheet = wb.createSheet ("xxx tabela"); // 3. Adicione a 0ª linha do cabeçalho da tabela na folha. A versão antiga POI tem um limite para o número de linhas do Excel Short Hssfrow Row = Sheet.Crearrow ((int) 0); // 4. Crie uma célula, defina o cabeçalho da tabela de valores e defina o cabeçalho da tabela para o centro HSSFCellStyle Style = wb.createCellStyle (); // Centering Format Style.Setalignment (hssfcellstyle.align_center); // Defina o cabeçalho da tabela HSSFCell Cell = Row.CreateCell (0); Cell.SetCellValue ("Header1 da tabela"); Cell.setCellStyle (estilo); célula = linha.createCell (1); Cell.SetCellValue ("Header2 da tabela"); Cell.setCellStyle (estilo); célula = linha.createCell (2); Cell.SetCellValue ("Header3 da tabela"); Cell.setCellStyle (estilo); célula = linha.createCell (3); Cell.SetCellValue ("cabeçalho da tabela 4"); Cell.setCellStyle (estilo); célula = linha.createCell (4); Cell.SetCellValue ("cabeçalho da tabela 5"); Cell.setCellStyle (estilo);Depois de gerar o formato do Excel, você deve escrever os dados para Excel:
// loop para escrever dados para se destacar para (int i = 0; i <lists.size (); i ++) {row = sheet.crerowerow ((int) i+1); Lista list = lists.get (i); // Crie uma célula e defina a linha de valor.createCell (0) .SetCellValue (list.getxxx ()); row.createCell (1) .setCellValue (list.getxxx ()); row.createCell (2) .setCellValue (list.getxxx ()); row.createCell (3) .setCellValue (list.getxxx ()); row.createCell (3) .setCellValue (list.getxxx ()); row.createCell (4) .setCellValue (list.getxxx ()); } O Excel resultante será então emitido como fluxo.
*Nenhuma caixa de download aparece
FileOutputStream out = new FileOutputStream ("e: /xxx.xls"); wb.write (out); out.Close ();*Popt up a caixa de download
String filename = "xxx tabela"; ByteArrayOutputStream OS = new ByteArrayOutputStream (); wb.Write (OS); byte [] content = os.tobytearray (); InputStream é = new ByteArrayInputStream (content); // Defina o parâmetro de resposta para abrir a página de download res.reset (); res.setContentType ("Application/vnd.ms-excel; charset = utf-8"); Res.SetHeader ("Content-Disposition", "Applement; filename =" + new String ((nome do arquivo + ".xls"). getBytes (), "ISO-8859-1")); ServletOutputStream out = res.getOutputStream (); BufferInputStream bis = null; BufferOutputStream bos = nulo; tente {bis = new bufferInputStream (IS); bos = new bufferedoutputStream (out); byte [] buff = novo byte [2048]; int bytesread; // Loop simples de leitura/gravação. while (-1! = (bytesread = bis.read (buff, 0, buff.length))) {bos.write (buff, 0, bytesread); }} Catch (Exceção e) {// TODO: lidar com a exceção e.printStackTrace (); } finalmente {if (bis! = null) bis.close (); if (bos! = null) bos.close (); } Depois de concluir as operações acima, você pode pular para outras páginas.
Ao mesmo tempo, o POI também pode exibir o Upload do Excel e a análise na página da web. Fique atento a este outro resumo do artigo!
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.