1. Introdução ao conceito
Apachepoi é uma biblioteca de código aberto da Apache Software Foundation. O POI fornece programas de APIs para Java para ler e escrever arquivos de formato do Microsoft Office.
2. Código relacionado à função
1. Descrição do ambiente: JDK1.7+Tomcat7+Mola
2. Configuração do arquivo de configuração
Adicione dependências de POI necessárias no arquivo POM
<!-Adicionar suporte POI-> <Depence> <PuerpId> org.apache.poi </groupiD> <TRATIFACTID> poi </sutifactId> <versão> 3.13 </version> </dependency> <pendency> <puerpyid> org.apache.poi </grupid>
Upload do arquivo de configuração Spring-mvc.xml
<bean id = "multipartResolver"> <!-codificação padrão-> <propriedade name = "defaultEncoding" value = "utf-8" /> <!-Valor máximo do tamanho do arquivo-> <names name = "maxuploadsize" value = "10485760000" /> <!-máximo no-> </ Bean>
3. Classes de ferramentas relacionadas e redação de código
Excel Parsing Tool Class (ImportExcelutil.java)
pacote com.jointem.hrm.utils; importar org.apache.poi.hssf.usermodel.hssfworkbook; importar org.apache.poi.ss.usermodel.cell; importação org.apache.poi.ss.uModel.row; import.apache.poiii.poi.ss.row; org.apache.poi.ss.usermodel.workbook; importar org.apache.poi.ss.util.cellrangeaddress; importar org.apache.poi.xssf.usermodel.xsSfworkbook; import java.io.ioException; importAmal.InputrenStreams; java.text.simpledEformat; importar java.util.ArrayList; importar java.util.list;/*** criado por Jenking em 2017/9/8. */classe pública ImportExcelutil {private final Static String Excel2003L = ". XLS"; // 2003- Versão do Excel Private Final Static String Excel2007U = ". XLSX"; // 2007+ Versão do Excel/** * Descrição: Obtenha os dados no fluxo de IO e monte -os em uma lista <LISTA <Object>> objeto * @param em, arquivo de arquivo * @return * @throws ioexception */public list <list>>> getBankListByExcel (inputStream em, string fillename) Throws {Exception { // Crie trabalho da pasta de trabalho do Excel = this.getworkbook (em, nome do arquivo); if (null == work) {lança nova exceção ("Crie uma planilha do Excel como vazia!"); } Folha = nulo; Linha linha = nulo; Célula celular = nulo; list = new ArrayList <List <Bect>> (); // Tranquilidade Todas as folhas no Excel para (int i = 0; i <work.getNumberfSheets (); i ++) {Sheet = work.getSheetat (i); if (Sheet == NULL) {continuação;} // Tranquilidade todas as linhas no sistema de folha atual.out.println (Sheet.getLastrownum ()); para (int j = Sheet.getfirstrownum (); j <= Sheet.getLastrownum ()-11; j ++) {row = Sheet.getRow (j); // if (row == null || row.getfirstcellnum () == J) // {// continua; //} // taverse todo columns for (int y = row.getfirstCellnum (); y <row.getLastcellnum (); y ++) {Cell = row.getCell (y); if (this.ismergedregion (folha, j, y)) {li.add (this.getmergedRegionValue (folha, j, y)); } else {li.add (this.getCellValue (célula)); }} list.add (li); }} work.close (); lista de retorno; } / ** * Descrição: De acordo com o sufixo do arquivo, a versão do arquivo carregou de forma adaptável * @param Instr, FileName * @return * @throws Exception * / Public WorkBetworkbook (InputStream Instr, String FileName) lança a exceção {Work. WB = NULL; String filetype = filename.substring (filename.lastIndexof (".")); if (Excel2003L.Equals (FileType)) {wb = new HSSFWorkbook (Instr); // 2003-} else if (Excel2007U.Equals (FileType)) {wb = new XSSFWorkbook (Instr); // 2007+} else {lança nova exceção ("O formato de arquivo analisado está incorreto!"); } retornar wb; } / ** * Descrição: formate os valores na tabela * @param celular * @return * / public objeto getCellValue (célula) {Valor do objeto = null; Decimalformat df = new decimalformat ("0"); // Formato Número da sequência do caractere SimpleDateFormat sdf = new SimpleDateFormat ("AAAA-MM-DD"); // formato de data decimalformat df2 = new decimalformat ("0"); // Switch de número de formato (Cell.getCellType ()) {case Cell.Cell_Type_String: value = Cell.getRichStringCellValue (). GetString (); quebrar; case celular.cell_type_numeric: if ("general" .equals (Cell.getCellStyle (). getDataFormatString ())) {value = df.Format (Cell.getNumericCellValue ()); } else if ("m/d/yy" .equals (Cell.getCellStyle (). getDataFormatString ())) {value = sdf.format (Cell.getDateCellValue ()); } else {value = df2.Format (Cell.getNumericCellValue ()); } quebrar; Case Cell.Cell_Type_Boolean: Value = Cell.getBooleAnCellValue (); quebrar; case celular.cell_type_blank: value = ""; quebrar; Padrão: quebra; } retornar valor; } / ** * Obtenha o conteúdo da célula mesclada * @param folha * @param linha * @param coluna * @return * / public objeto getMergedRegionValue (folha, folha, int linha, int coluna) {int SheetMerGecount = SheetnummergedRegions (); for (int i = 0; i <SheetMerGecount; i ++) {CellRangeAdRest Ca = Sheet.getMergedRegion (i); int primeiroColumn = ca.getfirstcolumn (); int lastColumn = ca.getLastColumn (); int firstrow = ca.getfirstrow (); int lastrow = ca.getLastrow (); if (linha> = firstrow && line <= lastrow) {if (colun> = FirstColumn && colun <= lastColumn) {linha frut = sheet.getRow (firstrow); Célula fcell = Frow.getCell (FirstColumn); retornar this.getCellValue (fcell); }} retornar nulo; } / ** * Determine se é uma célula mesclada * @param folha * @param linha * @param coluna * @return * / public boolean ismergedregion (folha, folha, int linha, int coluna) {int sheetMergecount = sheetnummergedregions (); for (int i = 0; i <SheetMerGecount; i ++) {CellRangeAddress range = Sheet.getMergedRegion (i); int primeiroColumn = range.getfirstcolumn (); int lastColumn = range.getLastColumn (); int firstrow = range.getfirstrow (); int lastrow = range.getLastrow (); if (linha> = firstrow && line <= lastrow) {if (colun> = FirstColumn && colun <= lastColumn) {return true; }}} retorna false; }} Solicitar Controlador (Página de Processo Excel Importar Solicitação)
pacote com.poiexcel.control; importar java.io.inputStream; importar java.io.printwriter; importar java.util.list; importar javax.servlet.http.httpServletRequest; importar javax.servlet.http.httpServletResponse; importar org.springframework.tereotype.controller; importar org.springframework.web.bind.annotation.requestmapping; importar org.springframework.web.bind.annotation.requestmethod; importar org.springframework.web.bind.annotation.ResponseBody; importar org.springframework.web.multipart.multipartFile; importar org.springframework.web.multipart.multiparthttpServletRequest; importar com.poiexcel.util.importExcelutil; importar com.poiexcel.vo.infovo; @Controller @ReQuestMapping ("/uPloadexcel/ *") classe public uploadexcelcontrol {/** * Descrição: importar arquivo Excel através do envio tradicional do formulário * @param request * @throws excepção */@requestMapping (value = "upload.do", método = {requestmethod.get, requestMod.Port.PertMapping (value = "upload.do", Method = {requestmethod.get, requestmod.PertMappe Exceção lança {multiparthttpServletRequest multipartreCeSt = ((multiparthttpServletRequest) solicitação; InputStream in = null; Lista <LIST <BECT>> listOB = null; Arquivo multiparttFile = multipartrequest.getfile ("upfile"); if (file.isEmpty ()) {lança nova exceção ("o arquivo não existe!"); } in = file.getInputStream (); listOB = new ImportExcelUtil (). getBankListByExcel (in, file.getoriginalfilename ()); in.Close (); // O método de serviço correspondente pode ser chamado aqui para salvar os dados no banco de dados. Agora, apenas os dados são emitidos para (int i = 0; i <listOb.size (); i ++) {list <ject> lo = listob.get (i); InfoVo Vo = new InfoVo (); Vo.setCode (String.ValueOf (lo.get (0))); Vo.setName (String.ValueOf (lo.get (1))); Vo.SetDate (String.ValueOf (lo.get (2))); Vo.setMoney (String.ValueOf (lo.get (3))); System.out.println ("Informações de impressão-> instituição:"+vo.getCode ()+"nome:"+vo.getName ()+"time:"+vo.getdate ()+"ativo:"+vo.getMoney ()); } retornar "resultado"; } Código front-end
O front-end usa o componente de upload do arquivo FileInput of Bootstrap e precisa introduzir o FileInput.css, FileInput.js, zh.js, bootstrap.css, bootstrap.js, jQuery.min.js
<body> <h4> Informações de presença Entrada </h4> <form method = "post" ENCTYPE = "Multipart/form-data" id = "form1" action = "$ {PageContext.Request.ContextPath}/presença/uPloadexcel"> <input id = "file-zh" name = "upfile $ ('#file-zh'). fileInput ({idioma: 'zh', uploadUrl: '$ {PageContext.Request.ContextPath}/Atendimento/Uploadexcel', PermitidofileExtensions: ['xls', 'xlsx']}); </script> Objeto Vo, salve o objeto correspondente dos dados do Excel
pacote com.poiexcel.vo; // Converter cada linha do Excel em um objeto Public Class InfoVo {Private String Code; nome de string privado; data de string privada; dinheiro privado de cordas; public String getCode () {Código de retorno; } public void setCode (código da string) {this.code = code; } public string getName () {return name; } public void setName (nome da string) {this.name = name; } public String getDate () {Data de retorno; } public void setDate (string date) {this.date = date; } public string getMoney () {return Money; } public void setMoney (String Money) {this.money = Money; }}3. Exibição de efeito
1. Exibição da página
2. Informações de back -end de impressão
4. Resumo
Este exemplo gera apenas os dados importados no console e não persiste. Se você quiser persistir, basta ligar para a camada de serviço no local do comentário
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.