Exemplo: importar dados relevantes (arquivo Excel) e editar os dados do arquivo relevante.
Configuração do arquivo XML
Em seguida, configure o tamanho do arquivo a ser carregado no arquivo xml da primavera
<!-Carregar a interceptação do arquivo, defina o tamanho máximo do arquivo de upload 10m = 10*1024*1024 (b) = 10485760 bytes-> <bean id = "multipartresolver"> <nome da propriedade = "maxuploadSize" Value = "10485760" /> < /bean>
Configuração da interface JSP
<div> <form id = "sourcefile" name = "Sourcefile" action = "" method = "post" Enctype = "Multipart /form-Data"> <input type = "button" value = "add" onclick = "addairline ()" /> <input style = "margin-left: 20px;" id = "source_file" name = "sourcefile" type = "arquivo" value = "selecione arquivo" /> <input style = "margin-left: 20px;" Data-carregamento-text = "Não envie repetidamente" type = "submite" value = "upload" onclick = "uppolicy ()"> <input style = "margin-left: 20px;" type = "submite" value = "download modelo" onclick = "return DownloadTemplate ();"> </morm> </div>
arquivo js
function uppolicy () {document.sourcefile.action = "/login/policy/uploadcsv"; var submiturl = document.getElementById ("Sourcefile"). Atributos ["ação"]. $ .ajax ({type: "post", url: submiturl, dados: $ ('#Sourcefile'). Serialize (), Datatype: "JSON", SUCCESS: function (resultado) {var json = json.parse (resultado); if (json.flag == "0" | })}Configuração do controlador
@RequestMapping (value = "/uploadcsv", método = requestMethod.post) @ResponseBody public string uploadcsv (@RequestParam ("SourceFile") MultipartFile Sourcefile, httpServleTrequest Solicy, httpSetResponse) // obtenha o nome do arquivo string name = fontefile.getoriginalfilename (); // determina ainda se o arquivo está vazio (ou seja, determine se seu tamanho é 0 ou se seu nome é nulo) tamanho longo = fonte dofile.getSize (); if (nome == null || (""). igual (nome) && size == 0) retorna null; // Importação em lote. Parâmetros: Nome do arquivo, arquivo. booleano b = Batchimport (nome, fonte de origem); JsonObject jsonObject = new jsonObject (); if (b) {jsonObject.put ("sinalizador", 0); jsonObject.put ("Sucesso", "Importar em lote Excel com sucesso!"); } else {jsonObject.put ("sinalizador", 1); JsonObject.put ("Sucesso", "O importação do lote do Excel falhou!"); } return jsonObject.toString (); }A camada não é tão detalhada e o processamento é feito no controlador
public boolean Batchimport (nome da string, arquivo multipart -arquivo) {boolean b = false; // Crie e processos Excel Excelutils readexcel = new Excelutils (); // Parse Excel e obtenha uma coleção de informações do cliente. List <OtapolyModel> cpolicylist = readExcel.getexcelinfo (nome, arquivo); if (cpolicylist! = null) {b = true; } // Adicione iterativamente as informações (Nota: De fato, você pode usar diretamente o conjunto de cpolistilistas como um parâmetro aqui e usar a tag foreach para adicionar o arquivo de mapeamento correspondente de mybatis para adição de lote.) Para (otapolymodel Customer: Cpolicylist) {PolicyDao.InstetoTapolicy (Customer); } retornar b; }Classe de ferramentas Excelutils.java
Ou seja, os métodos chamados pelo ReadExcel.Getexcelinfo (nome, arquivo); declaração no método acima e em outros métodos relacionados
O Apache POI fornece APIs para programas Java para ler e escrever arquivos de formato do Microsoft Office. No entanto, antes de tudo, temos que julgar a versão do Excel e escolher uma pasta de trabalho diferente (a versão de 2003 corresponde ao HSSFWorkbook, e a versão de 2007 e acima corresponde ao XSSFWorkbook). Além disso, de um modo geral, primeiro copie o arquivo enviado pelo usuário cliente para o disco local do servidor e depois o leia a partir deste arquivo de cópia, evitando a perda ou corrupção de dados durante a leitura devido a exceções de rede ou outras condições do cliente.
pacote com.flight.inter.otaadapter.commons.util; import com.flight.inter.otaadapter.model.otapolicymodel; importar org.apache.poi.hssf.Usermodel.hssfworks; org.apache.poi.ss.usermodel.sheet; importar org.apache.poi.ss.usermodel.workbook; importar org.apache.poi.xssf.usermodel.xssfworkbook; import org.springframework.web.multipart.multiptill; org.springframework.web.multipart.commons.commonsmultipartFile; importar java.io.*; importar java.math.bigdecimal; importar java.util.arraylist; import java.util.date; import javan.util.list; */classe pública Excelutils {// Número total de linhas privadas int totalRows = 0; // número total de peças privadas int totalCells = 0; // receptor de mensagem de erro private string errorMsg; // Método de construção public Excelutils () {} // Obter número total de linhas public int getTotalRows () {return totalRows;} // obtenha o número total de colunas public int getTotalCells () {return totalCells;} // obtiver mensagem public string geterrorinfo () {Return ErrormSSSG; } / ** * Verifique o arquivo do Excel * @param filepath * @return * / public boolean valideExcel (string filepath) {if (filepath == null ||! (Wdwutil.isexcel2003 (FILEP) || wdwutil.isexcel2007 (filepath2003) (errrorm) || retornar falso; } retornar true; } /** * Leia o arquivo do Excel e obtenha a coleção de informações do cliente * @param * @return * /list public <OtapolyModel> getExcelinfo (nome do arquivo de string, mfile multipart -file) {// convert o molepartFile carregado pelo arquivo spring to commonSmultipartFile comOnsmmol // Obter arquivo de caminho de armazenamento local Arquivo = novo arquivo ("d: // fileUpload"); // Crie um diretório (seu nome de caminho é especificado pelo objeto de arquivo atual, incluindo qualquer caminho pai necessário.) Se (! File.exists ()) file.mkdirs (); // Crie um novo arquivo de arquivo file1 = novo arquivo ("d: // fileUpload" + new Date (). Gettime () + ".xlsx"); // Escreva o arquivo enviado no arquivo recém -criado, tente {cf.getfileitem (). Write (file1); } catch (Exceção e) {e.printStackTrace (); } // Inicialize a coleta da lista de informações do cliente <OtapolyModel> CustomerList = new ArrayList <OtapolyModel> (); // inicialize o fluxo de entrada inputStream é = null; tente {// verifique se o nome do arquivo está qualificado se (! validexcel (nome do arquivo)) {return null; } // Padrão se o arquivo é versão 2003 ou versão 2007 com base no nome do arquivo boolean isexcel2003 = true; if (wdwutil.isexcel2007 (nome do arquivo)) {isexcel2003 = false; } // instanciar o fluxo de entrada com base no arquivo recém -criado é = new FileInputStream (File1); // Leia as informações do cliente com base no conteúdo no Excel CustomerList = getExcelinfo (IS, ISEXCEL2003); is.close (); } catch (Exceção e) {e.printStackTrace (); } finalmente {if (is! = null) {try {is.close (); } catch (ioexception e) {is = null; E.PrintStackTrace (); }} retornar ao clientelist; } / *** Leia as informações do cliente com base no conteúdo no Excel* @param é fluxo de entrada* @param isexcel2003 é excel 2003 ou 2007 versão* @return* @throws ioexception* / public list <otapolyymodel> getExcelinfo (inputStream é, boolean isexcel2003) {late tente { / ** selecione a maneira de criar uma pasta de trabalho de acordo com a versão* / pasta de trabalho wb = null; // Quando o Excel é 2003 se (isexcel2003) {wb = new HSSFWorkbook (IS); } else {// Quando o Excel é 2007 wb = new XSSFWorkbook (IS); } // Leia as informações do cliente no Excel CustomerList = ReadExcelValue (WB); } catch (ioexception e) {e.printStackTrace (); } retornar ao clientelist; } /** * Leia as informações do cliente no Excel * @param wb * @return * /Lista privada <OtapolyModel> ReadExcelValue (pasta de trabalho WB) {// Obtenha a primeira planilha de shell = wb.getSheetat (0); // Obtenha o número de linhas no Excel this.TotalRows = Sheet.getphysicalNumberOfRows (); // Obtenha o número de colunas no Excel (presumivelmente há linhas) se (totalRows> = 1 && sheet.getRow (0)! = Null) {this.totalCells = sheet.getRow (0) .getPhySicalNumberOfcells (); } Lista <OTapolyModel> otapolymodEllist = new ArrayList <OtapolyModel> (); Otapolymodel otapolymodel; // Loop Excel Número da linha, começando na segunda linha. O título não é armazenado para (int r = 1; r <totalRows; r ++) {linha linha = chaphe.getRow (r); se (linha == nulo) continuar; otapolymodel = new otapolymodel (); tente {thread.currentThread (). Sleep (1); } catch (interruptedException e) {e.printStackTrace (); } otapolymodel.setpolicyId (System.currenttimemillis ()); // Coleção do Excel para (int c = 0; c <this.totalCells; c ++) {celular = row.getCell (c); if (null! = Cell) {if (c == 0) {otapolymodel.SetSource (Cell.GetStringCellValue ()); // fornecedor} else if (c == 1) {otapolicymodel.setVendee (Cell.getStringCellValue () // em canal de saída} if (Cell.getStringCellValue () == "All") {tripType = 0; } else if (Cell.getStringCellValue (). Equals ("Single-Way")) {triptype = 10; } else if (Cell.getStringCellValue (). Equals ("ida e volta")) {triptype = 20; } else if (Cell.getStringCellValue (). Equals ("voo direto único")) {triptype = 11; } else if (Cell.getStringCellValue (). Equals ("ida e volta")) {triptype = 12; } else if (Cell.getStringCellValue (). Equals ("ida e volta")) {triptype = 21; } else if (Cell.getStringCellValue (). Equals ("ida e volta")) {triptype = 21; } else if (Cell.getStringCellValue (). Equals ("ida e volta")) {triptype = 22; } otapolymodel.setTripType (triptype); // itinerário Tipo} else if (c == 3) {otapolymodel.setCarrier (Cell.getStringCellValValue (); cidade} else if (c == 5) {otapolymodel.setArrcity (Cell.getStringCellValue ()); // Landing City} else if (c == 6) {otapolymody.SetSalebegindatel (novo BigDecimal (Cell.getNumericCellValue ()). SetScale (0, bigdecimal.Round_Half_down) .longValue ()); // Data de início de vendas} else if (c == 7) {otapolymodel.SetSaleEnddatel (novo BigDecimal (Cell.getNumericCellValue ()). SetScale (0, BigDecimal.Round_Half_Down) .LongValue ()); // Data final de vendas} else if (C == 8) BigDecimal (Cell.getNumericCellValue ()). SetScale (0, BigDecimal.Round_Half_Down) .LongValue ()); // Data de início da viagem} else (C == 9) {otapolymodel.SetTravendDatel (novo BigDecimal (Cell.getNumericCellValue ()). SetScale (0, BigDecimal.Round_Half_Down) .longValue ()); // Data final da viagem} else if (c == 10) {int cabIntype = 9; if (Cell.getStringCellValue (). Equals ("All")) {Cabintype = 9; } else if (Cell.getStringCellValue (). Equals ("Economy Class")) {Cabintype = 1; } else if (Cell.getStringCellValue (). Equals ("Business")) {Cabintype = 2; } else if (Cell.getStringCellValue (). Equals ("First Class")) {Cabintype = 3; } otapolymodel.setCobIntype (CABINTYPE); // Nível de cadrift} else if (c == 11) {otapolymodel.setfdtype (Cell.getStringCellValue (). otapolicymodel.setCabin (Cell.getStringCellValue ()); // cat} else if (c == 13) {otapolymodel.setPriceBeGin (Cell.getNumericCellValue (); // preço mínimo} senão (c == 14) {orapolyelueTeUSeTeReTeRend.SetUSeReN); Preço} else if (c == 15) {otapolymodel.setlmoney (Cell.getNumericCellValue ()); // Economize dinheiro} else if (c == 16) {otapolicymodel.setfpercent (Cell.getNumericClvalue ()); otapolicymodel.setftPercent (Cell.getNumericCellValue ()); // por favor rebate} else if (c == 18) {int Carrierlimit = 2; if (Cell.getStringCellValue (). Equals ("Sim")) {Carrierlimit = 1; } else if (Cell.getStringCellValue (). Equals ("não")) {Carrierlimit = 0; } else if (Cell.getStringCellValue (). Equals ("None")) {Carrierlimit = 2; } otapolymodel.setCarrierLimit (Carrierlimit); // Restrições para a companhia aérea da fatura} else if (c == 19) {int transport = 2; if (Cell.getStringCellValue (). Equals ("sim")) {transport = 1; } else if (Cell.getStringCellValue (). Equals ("não")) {transport = 0; } else if (Cell.getStringCellValue (). Equals ("não")) {transport = 0; } else if (Cell.getStringCellValue (). Equals ("não")) {transport = 0; } else if (Cell.getStringCellValue (). Equals ("não")) {transport = 0; } else if (Cell.getStringCellValue (). Equals ("não")) {transport = 0; } else if (Cell.getStringCellValue (). Equals ("não")) {transport = 0; } else if (Cell.getStringCellValue (). Equals ("Unlimited")) {transport = 2; } otapolymodel.setTransport (transporte); // Suporte a transporte intermodal} else if (c == 20) {int sharedflight = 2; if (Cell.getStringCellValue (). Equals ("Sim")) {sharedflight = 1; } else if (Cell.getStringCellValue (). Equals ("não")) {sharedflight = 0; } else if (Cell.getStringCellValue (). Equals ("nenhum")) {sharedflight = 2; } otapolymodel.setsharedflight (sharedflight); // suporta voos compartilhados} else if (c == 21) {otapolymodel.setpstatus (Cell.getStringCellValue (). Equals ("Valid")? 1: 2); // status} se (c == 22) if (Cell.getStringCellValue (). Equals ("privado")) {FARETYPE = 1; } else if (Cell.getStringCellValue (). Equals ("Publication")) {Faretype = 2; } else if (Cell.getStringCellValue (). Equals ("Publication")) {Faretype = 2; } else if (Cell.getStringCellValue (). Equals ("All")) {FarEType = 0; } otapolymodel.setFaretype (Faretype); // Tipo de frete} else if (c == 23) {otapolicymodel.setlimitprice (novo bigdecimal (Cell.GetNumericCellValue (). if (c == 24) {int limitetransit = 2; if (Cell.getStringCellValue (). Equals ("All")) {limiteTransit = 2; } else if (Cell.getStringCellValue (). Equals ("aplicável")) {limitetransit = 0; } else if (Cell.getStringCellValue (). Equals ("não aplicável")) {limittransit = 1; } otapolymodel.setlimittransit (limitetransit); // limite de transição} else if (c == 25) {otapolymodel.setArcity (Cell.getStringCellValue ()); // transição city} else if (c == 26) {int limiteNation = 2; if (Cell.getStringCellValue (). Equals ("All")) {limitNation = 2; } else if (Cell.getStringCellValue (). Equals ("aplicável")) {limitNation = 0; } else if (Cell.getStringCellValue (). Equals ("não aplicável")) {limitNation = 1; } otapolymodel.setlimitnation (limite); // limite de nacionalidade} else if (c == 27) {otapolicymodel.setArcity (Cell.getStringCellValue ()); // nacionalidade} else (c == 28) {otapymodel.setUrname ( // Adicione o cliente otapolymodEllist.add (otapolymodel); } retornar otapolymodelist; }}Classe de ferramentas wdwutil.java
pacote com.flight.inter.otaadapter.commons.util;/*** Criado por ling.zhang em 2016/12/29. */ Public class Wdwutil {// @Description: Seja exceto de 2003, Return True is 2003 public estático booleano isexcel2003 (string filepath) {return filepath.matches ("^.+/. (? i) (xls) $"); } //@Descrição: Seja Excel de 2007, Return True é 2007 Public estático booleano isexcel2007 (string filepath) {return filepath.matches ("^.+//. (? I) (xlsx) $");}}Nota: Para fins de conveniência de leitura, o código acima é publicado pela primeira vez com o método pai e depois o método filho. Na edição real do código, o método filho geralmente é editado e depois editado com o método pai. Por exemplo, o acima deve primeiro editar o código da classe da ferramenta, editar o código da camada de serviço e, finalmente, editar o código do controlador.
Dessa forma, todo o processo está ok. Leve para testá -lo agora
Para um conteúdo mais emocionante, clique em "Spring Upload e baixe o tópico especial" para um estudo e pesquisa detalhados.
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.