Artikel ini membagikan Impor Batch Data Tabel Excel di Java untuk referensi Anda. Konten spesifik adalah sebagai berikut: impor java.awt.color; impor java.io.bytearrayInputStream; impor java.io.bytearrayoutputStream; impor java.io.file; impor java.io.fileInputStream; impor java.io.inputstream; impor java.lang.reflect.field; impor java.text.dateFormat; impor java.text.decimalformat; impor java.text.simpledateFormat; impor java.util.*; impor javax.swing.text.attributeset; impor javax.swing.text.element; impor javax.swing.text.html.css; impor javax.swing.text.html.htmldocument; impor javax.swing.text.html.htmleditorkit; impor cn.vrview.dev.common.exception.businessException; impor org.apache.commons.lang3.stringutils; impor org.apache.logging.log4j.logmanager; impor org.apache.logging.log4j.logger; impor org.apache.poi.hssf.usermodel.*; impor org.apache.poi.hssf.util.hssfcolor; impor org.apache.poi.ss.usermodel.*; impor org.apache.poi.ss.util.cellrangeaddress; impor org.apache.poi.xssf.usermodel.xssfcolor; impor org.apache.poi.xssf.usermodel.xssffont; impor org.apache.poi.xssf.usermodel.xssfworkbook; impor org.springframework.web.util.htmlutils; impor cn.vrview.dev.common.util.stringutil; kelas publik exceltools { / ** log* / logger static log = logManager.getLogger (); /** * Export excel * <p> * Usage: <br> * <code> List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();<br> * is = ExcelTools.exportXLS(dataList,new String[] {"createTime:Date","name:Name", "sex:Gender", "remark:Remark"}); * </code> * * @param collect * Data collection to be exported* @param header * Column to be exported* @return InputStream Return file stream*/ public static InputStream exportXLS(Collection<Map<String, Object>> collect, String[] header) { ByteArrayOutputStream out = new ByteArrayOutputStream(); Buku hssfworkbook = hssfworkbook baru (); coba {// tambahkan lembar hssfsheet sheet = book.createSheet ("sheet1"); // Tentukan himpunan nama kolom yang akan diekspor set <string> kolom = hashset baru <string> (); // atur warna latar belakang sel hssfcellstyle cellstyle = book.createCellstyle (); cellstyle.setFillPattern (hssfcellstyle.solid_foreground); cellstyle.setfillforeGroundColor (baru hssfcolor.yellow (). getIndex ()); // Hasilkan header hssfrow row = sheet.createrow (0); Hssfcell cell = row.createCell (0); cell.setCellStyle (CellStyle); cell.setCellValue ("urutan"); // Nomor kolom dimulai dari 1 int n = 1; // string header parse untuk (string str string: header) {string [] arr = str.split (":"); koloms.add (n + "," + arr [0]); // Tambahkan nama bidang untuk mengekspor dan mengikat ke nomor kolom n sel = row.createCell (n); cell.setCellStyle (CellStyle); cell.setCellValue (ARR [1]); n ++; } // menghasilkan baris data mulai dari 1, 0 adalah header int i = 1; // menghasilkan baris data untuk (peta <string, objek> peta: collect) {hssfrow datarow = sheet.createrow (i); // menghasilkan nomor urutan datalow.createCell (0) .setCellValue (i); // Hasilkan kolom lain untuk (kolom string: kolom) {// Gunakan koma untuk mendapatkan nama bidang, [0] adalah nomor kolom yang sesuai dengan header header. String columnName = column.split (",") [1]; // Hasilkan sel kolom nomor urutan = Dataarow.createCell (integer.parseint (column.split (",") [0])); Nilai string = ""; value = map.get (columnName) + ""; // Konversi ke "" if ("null" .Equals (value)) {value = ""; } RichTextString RichTextString = ProcessHtml (Book, Value); cell.getCellstyle (). SetWraptext (false); cell.setCellValue (RichTextString); } i ++; } book.write (out); out.close (); } catch (Exception e) {E.PrintStackTrace (); } return new ByteArrayInputStream (out.tobyteArray ()); } /** * Dapatkan data file excel <br> * Penggunaan: <br> * sheetInfo sheetInfo = exceltools baru (). SheetInfo baru (); <br> * sheetInfo.setrowtitle (0); Daftar <String> sheets = ArrayList baru <string> (); <br> * string sheetname = "sheet1"; sheets.add (sheetname); <br> * sheetinfo.setsheetnames (lembar); <br> * sheetInfo.setColumnsMapping(new String[] { "prodName:Product Name", * "prodSpec:Specification", "collectPrice:Price:" + {@link RegExpEnum} * RegExpEnum.NOTEMPTY_ISNUMBER, "priceUnit:Unit", "collectMarket:quotation market", * "prodLevel:level" }); <br> * peta <string, list> data = exceltools.getexcel (file baru (path), sheetInfo); * * @param * * @param sheetInfo * Initialization information* @return Map {sheet1:List} * @throws Exception * Exception */ @SuppressWarnings("rawtypes") public static Map getExcel(File f, SheetInfo sheetInfo, String excelType) throws Exception { return getExcel(new FileInputStream(f), sheetInfo, excelType); } @SuppressWarnings ({"rawTypes", "Uncecked"}) peta statis public getExcel (inputStream in, sheetInfo sheetInfo, string exceltype) melempar pengecualian {peta <string, string> columnsmap = new HashMap <String, String> (); // Daftar peta ekspresi verifikasi kolom <string> errmsg = new ArrayList <string> (); int errnum = 0; // Jumlah total kesalahan int errlimit = 10; // Batasi jumlah petunjuk kesalahan/ ** yang digunakan untuk menyimpan semua konten yang dibaca Excel sesuai dengan aturan yang ditentukan*/ peta excelinfo = hashmap baru (); Buku buku kerja = null; coba {if (exceltype.equals ("xls")) {book = new hssfworkbook (IN); // Lempar BusinessException baru ("Versi Excel terlalu rendah, silakan gunakan versi 2007 atau di atas (ekstensi: xlsx)"); } else {book = new XSFWorkBook (IN); }} catch (outofmemoryError e) {lempar runimeException baru ("File Excel saat ini terlalu besar, silakan periksa apakah ada data kosong yang tidak valid di setiap tabel lembar, termasuk data baris dan kolom dengan format dan wireframe, silakan hapus data yang tidak valid ini! Ukuran file Excel normal [dalam 1m]"); } // checkTitle (buku, sheetinfo); // Dapatkan jumlah lembar kerja int sheetnum = sheetInfo.getsheetnames (). Size (); // Loop semua worksheet dan baca data di dalam untuk (int sheetIndex = 0; sheetIndex <sheetnum; sheetIndex ++) {// Dapatkan objek worksheet saat ini string sheetname = htmlutils.htmlunescape (sheetInfo.getsheetnames (). Get (sheetindex)); Peta <string, string> validAteMap = new HashMap <string, string> (); untuk (string mapstr: sheetInfo.getColumnsmapping (). get (sheetname)) {string [] arr = mapstr.split (":"); columnsmap.put (arr [1], arr [0]); if (arr.length == 3) {// Jika ekspresi verifikasi tidak kosong, tambahkan ke peta ke validAteMap.put (arr [1], arr [2]); }} Sheet sheet = book.getsheet (sheetname); if (null == sheet) {lempar runtimeException baru (string.format ("Gagal mendapatkan tabel, harap konfirmasi apakah lembar"%s "ada di excel", sheetname)); } // Digunakan untuk menyimpan konten data di worksheet list sheetlist = new arraylist (); // Dapatkan jumlah baris di tabel saat ini int rows = sheet.getlastrownum (); // Dapatkan jumlah kolom dalam kolom int tabel saat ini = sheet.getRow (sheetInfo.getrowTitle ()). GetLastCellNum (); if (baris <= sheetInfo.getrowTitle ()) {// Jika tabel saat ini tidak memiliki data yang diperlukan, lanjutkan loop berikutnya; } // Dapatkan daftar konten Judul Worksheet saat ini <string> titLelist = ArrayList baru <string> (); // Loop setiap sel di setiap baris dan baca nilai di baris sel titlerow = sheet.getRow (sheetInfo.getrowTitle ()); untuk (int jj = 0; jj <kolom; jj ++) {cell cellTitle = titlerow.getCell (jj); if (cellTitle! = null) {int row = cellTitle.getRowIndex (); int kolom = cellTitle.getColumnIndex (); if (ismergedregion (lembar, baris, kolom)) {titlelist.add (getmergedregionValue (lembar, baris, kolom)); } else {titlelist.add (getCellValue (cellTitle)); }} else {lempar runtimeException baru ("Table Header Read ERROR, saat ini diatur ke" th " + (sheetInfo.getrowTitle () + 1) +" baris <br/> konten header tabel adalah: " + titlerow +", silakan periksa apakah itu benar. Jika ada pengecualian, Anda dapat menghapus format header dan repasta); " System.out.println (Titlelist); (Stringutils.deletewhitespace (t) .EqualSignorecase (colarr [1])) {termasuk = true break; Judul untuk (int i = sheetinfo.getrowTitle () + 1; i <= baris; i ++) {peta rowmap = hashmap baru (); 0; columnsmap.keyset ()) {if (stringutils.deletewhitespace (columnTitle) .equalsignorecase (judul)) {columnmapping = columnsmap.get (judul); if (exceltype.equals ("xls")) {hssfcolor color = (hssfcolor) cellstyle.getFillforeGroundColorColor (); Color = (XSSFColor) CellStyle.getfillforeGroundColorColor (); 0 &&! Stringutil.isempty (value)) {string rowspan = ""; cell.getCellComment ()! = NULL) {//system.out.println(columnMapping+"@Comment:"+Cell.getCellComment (). GetString ()); = "; (! Stringutil.isempty (validateReg)) {if (value.matches (validateReg)) {rowmap.put (columnmapping, value)} else {errnum ++; [" + validateRegMSg +"] </br>/n ");}}} else {if (stringutil.isempty (columnMapping)) {lanjutan;} else {// int row = cell.getRowIndex (); // int column = cell.getColumnIndex (); // iferDex (); // columner = cell.getColumnInndex (); // iferging (iSmerging.OlMoling = colum colum = cell. GetMergedregionValue (Sheet, Row, Colom)); > errlimit) {errmsg.add ("Template data yang Anda impor terlalu banyak kesalahan format (total" + errnum + "item), silakan periksa apakah data templat itu benar!"); RunimeException ("tes"); Daftar <String> errmsg = ArrayList baru <string> (); (arr.length == 3) {// Jika ekspresi verifikasi tidak kosong, tambahkan ke peta ke validAtemap.put (arr [1], arr [2]); // Dapatkan jumlah worksheet int sheetnum = book.getNumberofsheets (); // loop semua lembar kerja dan baca data di dalamnya untuk (int sheetIndex = 0; sheetIndex <sheetnum; sheetIndex ++) {// Get the Worksheet Sheet Sheet = Book.getsheet (sheetindex); ArrayList (); titlerow.getLastCellNum (); if (kolom! = SheetInfo.getColumnsmapping (). Get ("Columns"). Time Throw BusinessException baru ("Format file salah, silakan pilih kembali atau unduh template"); titlelist.add (titlerow.getcell (jj) .getStringCellValue ()); (! Titlelist.contains (s.split (":") [1])) {// errmsg.add ("'" + sheet.getsheetname () + "' Tabel '" + S // + "' setiap piring." baris, dan membaca dari baris di bawah judul untuk (int i = sheetinfo.getrowTitle ()+1; i <= baris; i ++) {peta rowmap = new hashMap (); "." ValidAteMap.get (ColumnTitle)) {// Verifikasi ekspresi reguler Regexpenum EUM = RegExpenum.ValueOf (ValidAteMap .get (ColumnTitle)); (value.matches (validateReg)) {rowmap.put (columnmapping, value);} else {errnum ++ "</br>/n"); // errmsg.add (Template data yang Anda impor terlalu banyak kesalahan format (total " + errnum +" item), silakan periksa dengan cermat apakah data templat itu benar! "); Operasi, Tabel Inisialisasi Informasi** @Author: Ji le* @Date: 2013-12-2 1:43:04 pm* @since: 1.0*/ Public Class SheetInfo {/ ** Baris di mana judul itu berada, NAMA ATRIBUTER PRIBADI PRIBADI PRIBADI PRIBAD. Columnsmapping; / ** Nama lembar yang perlu dibaca* / Daftar publik <string> sheetnames = new ArrayList <string> (); } else {this.sheetnames = sheetnames;}} public sheetinfo () {// Jika sheetnames tidak ditentukan, nilai default diberikan "sheet1" if (null == sheetnames || sheetnames.size () == 0) {sheetnames.add ("sheet1"); setRowTitle (int rowTitle) {this.rowtitle = rowTitle; SetSheetNames (Daftar <String> Sheetnames) {this.sheetnames = sheetnames;}} / **** kelas enum internal** @author: jile* @date: 2013-12-2 1:43:24 pm* @since: 1.0* / public enum regexpenum { / ** nox kosong ** tidak ada* /** harus menjadi angka*/iSnumber ("tidak dapat menjadi angka", "// d*"),/** tidak kosong dan angka*/notempty_isnumber ("tidak dapat menjadi kosong dan nomor public; Regexpenum (Teks String, Nilai String) {this.text = Text; WB, string html) {RichTextString RT = NULL; StringBuffer (); untuk garis int = 0, lastpos = -1; lastpos <doc.getLength (); lines ++) {// if (line> 0) {// sb.append ('/n'); line.getElementCount (); wb.getCreationHelper (); line.getElementCount (); Log.warn (E.GetMessage ()); // E.PrintStackTrace (); Atribute as = fragment.getAttributes (); as.getAttribute (attrib) .getClass (). getDeclaredfield ("c"); HSSFFONT && WB dari HSSFWorkbook) {hssfpalette pal = ((hssfworkbook) wb) .getcustompalette (); font) .setColor (col.getIndex ()); GetmergedregionRow (lembar sel, sel sel) {// Dapatkan berapa banyak sel yang digabungkan ada int sheetmergercount = sheet.getnummergeSt (); firstc = ca.getFirstColumn (); (Cell.getrowIndex () == Firstr) {return lastr - Firstr}}} return 0; 0; LASTROW) {if (kolom> = FirstColumn && Column <= LastColumn) {Row Frow = Sheet.getRow (FirStrow) * Kolom Subscript * @Return */ Public static boolean ismergedregion (lembar lembar, int kolom int) {int sheetmergecount = sheet.getnummergingregion (); range.getLastColumn (); @Return */ @suppresswarnings ("tidak digunakan") Boolean pribadi telah HASMERGED (lembar lembar) {return sheet.getNummergeRegions ()> 0? @SuppressWarnings ("tidak digunakan") void mergeregion pribadi (lembar lembar, int firstrow, int lastrow, int firstcol, int lastcol) {sheet.addmergedregion (cellrangeAddress (firstrow, lastrow, lastcol, lastcol)); getCellValue (sel sel) {if (cell == null) return ""; } else if (cell.getCellType () == cell.cell_type_formula) {return cell.getCellformula (); SimpleDateFormat ("yyyy-mm-dd"); adalah 3) Sedemaja SDF = new SimpleDateFormat ("yyyy-mm-dd"); cell.getNumericCellValue (); ") .Replace (String.ValueOf ((Char) 65279)," ")); Xssfcolor (color.yellow) .getArgbHex (). Substring (2)); RGB [0], RGB [1], B = RGB [2]; rfString = "B"; 11) RSString = "B"; / 16; = ValueOf (Green); = 15) GSString = "F"; 13) bfstring = "D" if (rBlue == 13) BSString = "D"; Lihat halaman from.jsp lagi
<body> <div> <form id="mainform" action="${ctx}/bom/ciscaseaction/${action}" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <a href="${ctx}/static/Case import template.xls" rel="external nofollow" >Download Template </a> </form> </div> <script type = "text/javascript"> $ (function () {$ ('#MainForm'). Form ({Onsubmit: function () {var isValid = $ (this) .form ('validate'); return isValid; // return false ke Iminal Formulir) .form ('validate'); return isValid; }}); </script> </body>Antarmuka utama JSP
Salin kode sebagai berikut: <a href = "javaScript (0)" rel = "nofollow eksternal" polos = "true" iconcls = "ikon-standar-application-o go" onclick = "importAction ()"> impor </a>
// Impor fungsi importAction () {d = $ ("#dlg"). Dialog ({title: 'case impor', lebar: 500, tinggi: 500, href: '$ {ctx}/bom/ciscaseAction/impor/', maximizable: true, modal: true, bom/ciscaseaction/impor/', maximizable: true, modal: true, togtons: [{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{') ({ $ ('#MainForm'). }Efek mengklik pada halaman adalah bahwa mengklik Impor akan melompat ke halaman From.jsp
Lihatlah lapisan pengontrol lagi
/ *** Halaman Impor*/ @RequestMapping (value = "ImportAction", Method = RequestMethod.get) Public String ImportForm (Model Model) {Model.AdDattribute ("Action", "Impor"); return "System/CiscaseActionImoPortform"; } / *** Impor* / @RequestMapping (value = "Impor", Method = requestMethod.post) @ResponseBody Public String ImportForm (@RequestParam ("File") MultipartFile MultipartFile, Model Model) Lempar Pengecuali mengembalikan "kesuksesan"; } Lapisan Layanan
/ *** Kasing impor*/ @suppresswarnings ({"rawTypes", "Uncecked"}) unggah public void (multipartfile multipartFile) melempar pengecualian {inputStream inputStream = multipartfile.getInputStream (); Exceltools exceltools = exceltools baru (); Exceltools.sheetinfo sheetinfo = exceltools.new sheetinfo (); sheetinfo.setrowtitle (0); Kolom peta = hashmap baru (); columns.put ("kolom", string baru [] {"name: case name", "violatelaw: break of law", "punishbasis: punishbasis"}); sheetinfo.setColumnsmapping (kolom); Daftar <hashMap <string, string >> mapList = exceltools.getexcel (inputStream, sheetInfo); untuk (int i = 0; i <maplist.size (); i ++) {hashMap <string, string> map = mapList.get (i); String name = map.get ("name"); if (stringutils.isempty (name)) {throw new BusinessException ("th" + (i + 2) + "Nama kasing tidak dapat kosong"); } String pelanggaranLaw = MAP.get ("Violatelaw"); String hukumanbasis = map.get ("punishbasis"); Ciscaseaction ciscaseAction = ciscaseAction baru (); ciscaseAction.setname (name); ciscaseaction.setviolatelaw (violatelaw); ciscaseaction.setpunishbasis (punishbasis); this.insert (ciscaseAction); // Memanggil metode penyisipan dari lapisan yang sama}} Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.