Este artigo compartilha a importação do lote dos dados da tabela Excel em Java para sua referência. O conteúdo específico é o seguinte: importar java.awt.color; importar java.io.byteArrayInputStream; importar java.io.byteArrayOutputStream; importar java.io.file; importar java.io.fileInputStream; importar java.io.inputStream; importar java.lang.reflect.field; importar java.text.dateFormat; importar java.text.decimalformat; importar java.text.simpledateFormat; importar java.util.*; importar javax.swing.text.attributeset; importar javax.swing.text.Element; importar javax.swing.text.html.css; importar javax.swing.text.html.htmldocument; importar javax.swing.text.html.htmleditorkit; importar cn.vrview.dev.common.exception.businessException; importar org.apache.commons.lang3.StringUtils; importar org.apache.logging.log4j.logmanager; importar org.apache.logging.log4j.logger; importar org.apache.poi.hssf.usermodel.*; importar org.apache.poi.hssf.util.hssfcolor; importar org.apache.poi.ss.usermodel.*; importar org.apache.poi.ss.util.cellrangeAddress; importar org.apache.poi.xssf.usermodel.xssfcolor; importar org.apache.poi.xssf.usermodel.xssffont; importar org.apache.poi.xssf.usermodel.xssfworkbook; importar org.springframework.web.util.htmlutils; importar cn.vrview.dev.common.util.stringutil; classe pública ExceLTools { / ** log* / logger estático privado log = logManager.getLogger (); /** * Exportar Excel * <p> * Uso: <br> * <code> LIST <pap <string, objeto >> Datalist = new ArrayList <map <string, object >> (); <br> * IS = Exceltools.exportXls (Datalist, new String [] {"CreateTime: Date", "Nome:" "; * </code> * * @param coleciona * Coleção de dados a ser exportada * @param cabeçalho * coluna a ser exportada * @return inputStream Retorno Stream de arquivo */ public estático inputStream ExportXLS (coleção <map <string, object >> colecionar, string [] Header) {ByTearArrayOutstream out = newTearAttUsTream (] String []) {ByTearArrayOutstream Out = newTearAttUsTream (]; Livro do HSSFWorkbook = new HSSFWorkbook (); tente {// Adicione uma folha HSSFSHEET = book.createSheet ("Sheet1"); // Defina o conjunto de nomes de colunas a serem exportados conjunto <string> colunas = new HashSet <String> (); // Defina a cor de fundo da célula HSSFCELLSTYLE CellStyle = book.createCellStyle (); CellStyle.setFillPattern (hssfcellstyle.solid_foreground); CellStyle.setFillForeRoundColor (novo hssfcolor.yellow (). getIndex ()); // gerar cabeçalho hssfrow linha = chaphe.crerowerow (0); HSSFCell Cell = Row.CreateCell (0); Cell.setCellStyle (CellStyle); Cell.SetCellValue ("Sequência"); // O número da coluna começa de 1 int n = 1; // String de cabeçalho de análise para (String str: cabeçalho) {String [] arr = str.split (":"); colums.add (n + "," + arr [0]); // Adicione o nome do campo para exportar e vincular ao número da coluna n célula = linha.createCell (n); Cell.setCellStyle (CellStyle); Cell.SetCellValue (arr [1]); n ++; } // gerar linhas de dados a partir de 1, 0 é o cabeçalho int i = 1; // gerar linhas de dados para (map <string, objeto> mapa: colecionar) {hssfrow dataarow = sheet.crerowerow (i); // gerar o número da sequência Dataarow.createCell (0) .SetCellValue (i); // Gere outras colunas para (coluna de string: colunas) {// use vírgulas para obter o nome do campo, [0] é o número da coluna para corresponder ao cabeçalho do cabeçalho. String columnName = column.split (",") [1]; // gerar a célula da coluna do número de sequência = Dataarow.CreateCell (Integer.parseint (columm.split (",") [0])); String value = ""; value = map.get (columnName) + ""; // converter para "" if ("null" .equals (value)) {value = ""; } RichtextString richtextString = processhtml (livro, valor); Cell.getCellStyle (). setWrapText (false); Cell.setCellValue (RichTextString); } i ++; } book.write (out); out.Close (); } catch (Exceção e) {e.printStackTrace (); } retornar novo byteArrayInputStream (out.tobyteArray ()); } /** * Obtenha dados do Arquivo Excel <br> * Uso: <br> * SheetInFo SheetInfo = news ExcelTools (). New SheetInfo (); <br> * SheetInfo.setRowTitle (0); List <Bring> Sheets = new ArrayList <Bring> (); <br> * String Sheetname = "Sheet1"; sheets.add (sheetname); <br> * SheetInfo.setSheetNames (folhas); <br> * SheetInfo.setColumnSmapping (new String [] {"ProdName: Nome do produto", * "ProdSpec: Specification", "CollectPrice: Price:" + {@link regexpenum} * regexpenum.notempty_isnumber, "PriceUnit: unidade", "Collectet. <br> * mapa <string, list> data = exceLools.Getexcel (novo arquivo (caminho), sheetInfo); * * @param * * @param SheetInfo * Informações da inicialização * @return mapa {Sheet1: list} * @THOWS Exceção * Exceção */ @suppresswarnings ("RawTypes") Public mapa estático getExcel (arquivo f, sheetInFoInFO, string ExceltyEnTe) THELTINFETINPE (RETURN (GETEXCELE (FILHEInFOInfo, String ExcelTyEn) } @Suppresswarnings ({"RawTypes", "desmarcado"}) mapa estático público getExcel (inputStream in, sheetInfo sheetInfo, string ExcelType) lança exceção {map <string, string> colunsmap = new hashmap <string, string> (); // Lista de mapas de expressão de verificação da coluna <String> errmsg = new ArrayList <String> (); int errnum = 0; // número total de erros int errlimit = 10; // limitar o número de prompts de erro/ ** usados para armazenar todos os conteúdos que o Excel lê de acordo com as regras especificadas*/ map Excelinfo = new Hashmap (); Livro da pasta de trabalho = nulo; tente {if (ExcelType.equals ("xls")) {book = new HSSFWorkbook (in); // Lança a nova BusinessException ("A versão do Excel é muito baixa, use a versão 2007 ou acima (Extensão: XLSX)"); } else {book = new XSSFWorkbook (in); }} Catch (outOfMemoryError e) {THRON RUNTimeException ("O arquivo do Excel atual é muito grande, verifique se há dados vazios inválidos em cada tabela de folhas, incluindo dados de linha e coluna com formato e estrutura de arame, exclua esses dados inválidos! Tamanho normal do arquivo do Excel [dentro de 1m]"); } // checkTitle (livro, SheetInfo); // Obtenha o número de planilhas int sheetnum = SheetInfo.getSheetNames (). Size (); // loop todas as planilhas e leia os dados para (int sheetIndex = 0; SheetIndex <Sheetnum; SheetIndex ++) {// Obtenha o objeto de planilha atual String SheetName = htmlutils.htmlunescape (SheetInfo.getSheetNames (). Get (SheetIndex)); Mapa <string, string> validatemap = new hashmap <string, string> (); para (String Mapstr: SheetInfo.getColumnsMapping (). Get (SheetName)) {String [] arr = Mapstr.split (":"); columsmap.put (arr [1], arr [0]); if (arr.Length == 3) {// Se a expressão de verificação não estiver vazia, adicione -o ao mapa ao validatemap.put (arr [1], arr [2]); }} Folha = book.getSheet (SheetName); if (null == Sheet) {lança a nova RunTimeException (String.Format ("Falha ao obter a tabela, confirme se a folha"%s "existe no Excel", SheetName)); } // usado para armazenar o conteúdo de dados na lista de planilhas SheetList = new ArrayList (); // Obtenha o número de linhas na tabela atual int linhas = Sheet.getLastrownum (); // Obtenha o número de colunas na tabela atual int colunas = sheet.getRow (SheetInfo.getRowtitle ()). GetLastcellnum (); if (linhas <= SheetInfo.getRowTitle ()) {// Se a tabela atual não tiver os dados necessários, continue o próximo loop; } // Obtenha a lista de conteúdo do título atual da planilha <String> titleList = new ArrayList <String> (); // loop todas as células em cada linha e leia o valor no título da linha da célula = Sheet.getRow (SheetInfo.getRowTitle ()); for (int jj = 0; jj <colunas; jj ++) {Cell Celltitle = titlerow.getCell (jj); if (CellTitle! = null) {int row = CellTitle.getRowIndex (); int colun = CellTitle.getColumnIndex (); if (ismergedregion (folha, linha, coluna)) {titleList.add (getMergedRegionValue (folha, linha, coluna)); } else {titleList.add (getCellValue (CellTitle)); }} else {lança a nova runwimeException ("Erro de leitura do cabeçalho da tabela, atualmente definido como" th " + (sheetinfo.getRowtitle () + 1) +" linha <br/> o conteúdo do cabeçalho da tabela é: " + titlerow +", por favor, verifique se está correto. System.out.println (titlelist); (Stringutils.DeleTewhitespace (T) .Equalsignorecase (colarr [1]) {incluir = break; para (int i = SheetInfo.getRowtitle () + 1; i <= linhas; i ++) {map rowmap = new hashmap (); <colunas; Columnsmap.keyset ()) {if (stringutils.deletewhitespace (columnTitle) .equalsignorecase (title)) {columnMapping = columnsmap.get (title); Cell.getCellStyle (); ConvertrgbtoHex (color.getTriPlet ())); Filterstr (célula + "); rowmap.put ("rowspan", lobo de linhas+columnmapping+"-"+valor+"-"+(mergrow+1)); rowmap.put (columnmapp+"@comentário", Cell.getCellComment (). GetString ()); Regexpenum.valueof (validatemap.get (columnTitle)); if (errnum <= errlimit) {errmsg.add ("th" + i + "line: [" + columnTitle + "】 Dados é: '" + value.trim () + "' não corresponde! Row = Cell.getRowIndex (); Sheetlist.Add (RowMap); correto! ");} lança a nova RunTimeException (errmsg.toString (). replaceall (" // [| //] "," "));} // if (true) throw new RunTimeException (" Teste "); Return Excelinfo;} list public static <HasHmap <string, string>> getExcel (getExcel) String> Columnsmap = novo hashmap <string, string> (); SheetInfo.getColumnsMapping (). para armazenar todos os conteúdos que excelem as Regras Especificadas*/ Lista Excelinfo = New ArrayList (); Sheetnum; Sheet.getRow (SheetInfo.getRowtitle ()); Businessception ("O formato do arquivo está incorreto, selete ou faça o download do modelo"); ArrayList <String> (); SheetInfo.getColumnsMapping (). Get ("Colunas"); existir! "); LONGE NOVA BUSINESSCECCECTION (" O formato do arquivo está incorreto, selete ou faça o download do modelo ");}} // comece a fazer loop em todas as linhas, lendo o valor de cada linha e lendo a linha abaixo do título para (int i = sheetInfo.getRowtitle ()+1; Sheet.getRow (i); Nome correspondente à coluna da célula columnmapping = Columnsmap.get (columnTitle); eum.getValue (); + columnTitle + "] Os dados são: '" + value.trim () + "' não corresponde! [" + validateregmsg + "] </br>/n"); Sheetlist); RUNTimeException (Errmsg.toString (). ReplaceAll ("// [| //]", ""); Localizado, a linha de partida é 0, não 1*/ privado rowtitle = 1; não é definido, o valor padrão é fornecido "Sheet1" se (null == SheetNames || SheetNames.size () == 0) {this.sheetNames.add ("Sheet1"); SheetNames.size () == 0) {SheetNames.add ("Sheet1"); setColumnsMapping (mapa <string, string []> columnsMapping) {this.columnsMapping = columnsMapping; @Date: 2013-12-2 13:43:24*@since: 1.0*/public enum regexpenum {/** não vazio*/no noticty ("não pode estar vazio", "(?! +$). +"),/** deve ser um número*/isNumber ("Número de um número", "// d*"),/** deve ser um número*/isnumber ("Número de um número", "// d*"), " número "," // d+");/** text */text de sequência privada;/** nível */private string valor; public string getText () {return text;} public string getValue () {return value;} private regexpenum (string text, string value) {this.text = text; this.value = value;}}}} @Return richtextstring */ @suppresswarnings ("não utilizado") Processo de richtextstring estático privado (hssfworkbook wb, string html) {richtextstring rt = null; kit.CreateFaultDocument (); sb.append ('/n'); fragment.getEnDoffset () - frag. Doc.getLength (); rt.ApplyFont (frag.GetFoffset () + linhas, fragmentação.GeTENDoffset () + linhas, font); */ Fonta estática privada GetFontfromFragment (Pasa de trabalho WB, fragmento de elemento) lança exceção {font font = wb.createfont (); (CSS.Attribute.Color.Equals (Attrib)) {Campo F = AS.GetAttribute (Attrib) .getClass (). GetDecaredfield ("C"); Xssfcolor (c)); (Hssffont). } public static int getMergedRegionRow (folha, célula) {// Obtenha quantas células mescladas existem int sheetmergerCount = Sheet.getnummergedRegions (); Iniciar a coluna, a coluna Firmc = Ca.getFirstColumn (); FirstC) {if (Cell.getRowIndex () == first) {return lastr - first; Sheet.getnummergetRegions () (linha> = Firstrow && ROW <= lastrow) {if (coluna> = FirstColumn && coluna <= lastColumn) {line Frow = Sheet.getRow (Firstrow); @param linha * Subscrito de linha * @param coluna * Subscrito da coluna * @return */ public estático booleano ismergedregion (folha, linha int, int coluna) {int sheetMergecount = sheetnummergen); range.getfirstcolumn (); Determine se a página da planilha contém células mescladas * * @param Sheet * @return * / @suppresswarnings ("não utilizado") Private Boolean Hasmerged (chinelos) {retorna. @param lastcol * coluna final * / @suppresswarnings ("não utilizados") Mergeregião vazia privada (folha, firstrow, int lastrow, int FirstCol, int lastcol) {Sheet.addmergedRegion (New CellRangeAddress (Firstrow, LasTrow * */ public static string getCellValue (célula) {if (célula == null) return ""; String.Valueof (Cell.getBooleArCellValue ()); {// Formato de data e tempo SimpledateFormat sdf = new SimpledateFormat ("AAs-MM-DD"); DD DD (Resolvada pelo formato ID da célula, o valor de ID é 3 1) SimpledFormat SDF = New SimpleDateFormat ("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "a String.Valueof (sdf.format (data); str.replace (String.Valueof (Char) 160), ") Xssfcolor (color.yellow) .getargbhex (). Substring (2)); RGB [0], G = RGB [1], B = RGB [2]; "B"; "B"; G % 16; String.Valueof (verde); "F"; else gSString = String.valueOf(rgreen); gFString = gFString + gSString; blue = b / 16; rblue = b % 16; if (blue == 10) bFString = "A"; else if (blue == 11) bFString = "B"; else if (blue == 12) bFString = "C"; else if (blue == 13) bFString = "D"; else BFSTRING BLET = BLUE == 15) BFSTRING = " = " Veja a página do.jsp novamente
<Body> <div> <form id = "mainform" action = "$ {ctx}/Bom/cisSeAction/$ {Action}" method = "post" Enctype = "multipart/form-dados"> <input type = "file" name = "file"/> <href = "$ {ctx}} modelo </a> </morm> </div> <script type = "text/javascript"> $ (function () {$ ('#mainform'). form ({OnsubMit: function () {var isValid = $ (this) .form ('valides'); retornar isValid; }); </script> </body>Interface principal JSP
Copie o código da seguinte forma: <a href = "javascript (0)" rel = "Nofollow externo" plana = "true" iconCls = "icon-standard-applic-go" OnClick = "ImportAction ()"> importar </a>
// importar função importAction () {d = $ ("#dlg"). Diálogo ({title: 'case import', width: 500, altura: 500, href: '$ {ctx}/BOM/cisCaseAction/importAction/', Maximizable: True: Modal: True, Buttons: [{text: ':' Import ',', ',', ', maximizable: True: Fungal: True, Buttons: [{text:': ' }}, {text: 'cancel', manipulador: function () {d.Panel ('Close'); }O efeito de clicar na página é que clicar em Importar irá para a página do.jsp
Olhe para a camada do controlador novamente
/ *** Importar página*/ @RequestMapping (value = "importAction", Method = requestMethod.get) public String importForm (modelo modelo) {Model.addattribute ("Action", "import"); retornar "Sistema/CISSEACTIONIMOPORTFORM"; } / *** importar* / @RequestMapping (value = "import", métod = requestMethod.post) @ResponseBody public String ImportForm (@RequestParam ("arquivo") MultipartFile, modelo, modelo) lança exceção {CISSEACTIONSERVICE.UPLOAD (MultipartFile); retornar "sucesso"; } Camada de serviço
/ *** Case de importação*/ @suppresswarnings ({"RawTypes", "desmarcada"}) Upload public void (multipartFile multipartFile) lança exceção {inputStream inputStream = multipartFile.getInputStream (); ExceltOols ExceltOols = new ExceltOols (); ExceltOols.SheetInfo SheetInfo = ExceltOols.New SheetInfo (); SheetInfo.setRowTitle (0); Colunas de mapa = new hashmap (); colums.put ("colunas", new string [] {"nome: nome do caso", "Violatelaw: Break of Law", "PunishBasis: PunishBasis"}); SheetInfo.setColumnSmapping (colunas); Lista <hashmap <string, string >> mapList = exctoLools.getexcel (inputStream, sheetInfo); for (int i = 0; i <pList.size (); i ++) {hashmap <string, string> map = mapList.get (i); Nome da string = map.get ("nome"); if (stringUtils.isEmpty (nome)) {tiro a nova BusinessException ("th" + (i + 2) + "o nome do gabinete não pode estar vazio"); } String violationlaw = map.get ("violatelaw"); Punição de stringbasis = map.get ("punishbasis"); CISSEACTION CISSEACTION = NOVA CISSEACTION (); CISSEACTION.setName (nome); CISSEACTION.SETVIOLATELAW (VIOLATELAW); CISSEACTION.setPunishBasis (PunishBasis); this.Insert (CISSEACTION); // chamando o método de inserção da mesma camada}} 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.