例:関連するデータ(Excelファイル)をインポートし、関連するファイルデータを編集します。
XMLファイルの構成
次に、スプリングXMLファイルにアップロードするファイルのサイズを構成します
<! - ファイルインターセプトをアップロードし、最大アップロードファイルサイズ10m = 10*1024*1024(b)= 10485760バイトを設定します - > <bean id = "Multipartresolver"> <プロパティ名= "MaxuploAdsize" Value = "10485760" /> < /bean> < /bean>>
JSPインターフェイス構成
<div> <form id = "sourceFile" name = "sourceFile" action = "" method = "" post "enctype =" multipart /form-data "> <input type =" button "value =" add "onclick =" addairline() " /> <入力スタイル="マージン左:20px; " id = "source_file" name = "sourcefile" type = "file" value = "select file" /> <input style = "margin-left:20px;" data-loading-text = "繰り返し送信しないでください" type = "" value = "upload" onclick = "uppolicy()"> <input style = "margin-left:20px;" type = "submit" value = "template" onclick = "return downloadtemplate();"> </form> </div>
JSファイル
function uppolicy(){document.sourcefile.action = "/login/policy/uploadcsv"; var submiturl = document.getElementById( "sourceFile")。属性["action"]。value; $ .ajax({type: "post"、url:submiturl、data:$( '#sourcefile')、serialize()、datatype: "json"、success:function(result){result){result){result); if(json.flag == "0" || json.flag == "; })}コントローラー構成
@RequestMapping(value = "/uploadcsv"、method = requestmethod.post)@responsebody public string uploadcsv(@requestfile ")multipartfile sourcefile、httpservletrequest request、httpservletresponse応答) //ファイル名を取得する文字列name = sourcefile.getoriginalfilename(); //さらに、ファイルが空であるかどうか(つまり、サイズが0かどうか、その名前がnullかどうかを判断します)long size = sourcefile.getSize(); if(name == null ||( "")。equals(name)&& size == 0)return null; //バッチインポート。パラメーター:ファイル名、ファイル。 boolean b = batchimport(name、sourcefile); jsonobject jsonobject = new jsonobject(); if(b){jsonobject.put( "flag"、0); jsonobject.put( "success"、 "バッチインポートExcelに正常に!"); } else {jsonobject.put( "flag"、1); jsonobject.put( "success"、 "バッチインポートExcel Failed!"); } return jsonobject.toString(); }レイヤー化はそれほど詳細ではなく、処理はコントローラーで行われます
public boolean batchimport(string name、multipartfileファイル){boolean b = false; // Excelutils readexcel = new Excelutils()を作成して処理します。 // Excelを解析し、顧客情報のコレクションを取得します。リスト<OtapolicyModel> cpolicylist = readexcel.getexcelinfo(name、file); if(cpolicylist!= null){b = true; } //情報を繰り返し追加します(注:実際、ここでパラメーターとしてcpolicylistセットを直接使用し、foreachタグを使用して、バッチ追加のためにMybatisの対応するマッピングファイルを追加できます。 } burten b; }ツールクラスExcelutils.java
つまり、readexcel.getexcelinfo(name、file)によって呼び出される方法。上記の方法およびその他の関連方法のステートメント
Apache Poiは、Microsoft Officeフォーマットアーカイブを読み書きするためのJavaプログラムを提供します。ただし、まず第一に、Excelバージョンを判断して別のワークブックを選択する必要があります(2003年バージョンはHSSFWorkBookに対応し、2007年以降はXSSFWorkBookに対応しています)。さらに、一般的に言えば、最初にクライアントユーザーによってアップロードされたファイルをサーバーのローカルディスクにコピーし、このコピーファイルから読み取り、クライアントのネットワークの例外やその他の条件により、読み取り中にデータの損失または腐敗を回避します。
パッケージcom.flight.inter.otaadapter.commons.util; Import com.flight.inter.otaadapter.otapolicymodel; Import org.apache.poi.hssf.usermodel.hssfworkbook; Import org.apache.poi.ss.s.poi.s.poi.s.poi.s.poi.s.poi.s.poi.s.poi.s.poi.s.poi.s.poi.s.s.poi.s.s.poi.s.s.poi.smodel.cell; org.apache.poi.ss.usermodel.sheet; Import org.apache.poi.ss.usermodel.workbook; Import org.apache.poi.xssf.usermodel.xsfworkbook; Import org.springframework.web.web.multipart.multipartfile; Import; org.springframework.web.multipart.commons.commonsmultipartfile; Import java.io。*; import java.math.bigdecimal; Import java.util.date; import java.util.list; */public class excelutils {// rowsの合計数private int totalRows = 0; //ピースの総数プライベートint totalcells = 0; //エラーメッセージ受信機プライベート文字列ERRORMSG; // Construction Method public excelutils(){} // rowsの合計数を取得しますpublic int gettotalrows(){return totalrows;} } / ** * excel fileの検証 * @param filepath * @return * / public boolean validateexcel(string filepath){if(filepath == null ||!(wdwutil.isexcel2003(filepath)|| wdwutil.isexcel2007(filepath)))) falseを返します。 } trueを返します。 } /** * excelファイルを読んで、顧客情報コレクションを取得 * @param * @return * /public list <otapolicymodel> getexcelinfo(string filename、multipartfile mfile){//スプリングファイルによってアップロードされたマルチパートファイルを変換します。 //ローカルストレージパスfile = new file( "d:// fileupload"); //ディレクトリを作成します(そのパス名は、必要な親パスを含む現在のファイルオブジェクトによって指定されます。)if(!file.exists())file.mkdirs(); //新しいファイルfile1 = new fileを作成する( "d:// fileupload" + new date()。getTime() + ".xlsx"); //アップロードされたファイルを新しく作成したファイルに書き込むtry {cf.getFileItem()。write(file1); } catch(Exception e){e.printstacktrace(); } //顧客情報リストのコレクションを初期化<otapolicymodel> customerlist = new ArrayList <OtaPolicyModel>(); //入力ストリームの初期化inputstream is = null; try {//ファイル名が適格かどうかを確認しますif(!validateExcel(filename)){return null; } //ファイルがファイル名に基づいてバージョン2003またはバージョン2007であるかどうかのデフォルトBOOLEAN ISEXCEL2003 = true; if(wdwutil.isexcel2007(filename)){isexcel2003 = false; } //新しく作成されたファイルに基づいて入力ストリームをインスタンス化します= new FileInputStream(file1); // excelのコンテンツに基づいて顧客情報を読むcustomerlist = getexcelinfo(is、isexcel2003); is.close(); } catch(Exception e){e.printstacktrace(); }最後に{if(is!= null){try {is.close(); } catch(ioexception e){is = null; e.printstacktrace(); }} customerlistを返します。 } / *** excelのコンテンツに基づいて顧客情報を読む* @paramは入力ストリームです* @param isexcel2003はexcel 2003または2007バージョン* @return* @throws ioexception* / public list <otapolicymodel> getexcelinfo(inputstream is、boolean isexcel2003){null; { / **バージョンに従ってワークブックを作成する方法を選択してください* /ワークブックwb = null; // excel is 2003の場合if(isexcel2003){wb = new hssfworkbook(is); } else {// excelが2007年の場合WB = new XSSFWorkBook(is); } // excel customerlist = readexcelvalue(wb)で顧客の情報を読む; } catch(ioexception e){e.printstacktrace(); } customerlistを返します。 } /** * excelの顧客の情報を読む * @param wb * @return * /private list <otapolicymodel> readexcelvalue(workbook wb){//最初のシェルシートシート= wb.getsheetat(0); // excel this.totalrows = sheet.getphysicalNumberofrows()で行数を取得します。 // excelの列の数を取得します(おそらく行があります)if(totalrow> = 1 && sheet.getrow(0)!= null){this.totalcells = sheet.getrow(0).getphysicalnumbumbers(); } list <otapolicymodel> otapolicymodellist = new ArrayList <OtaPolicyModel>(); otapolicymodel otapolicymodel; // 2番目の行から開始するループエクセル行番号。タイトルは(int r = 1; r <totalRows; r ++){row row = sheet.getrow(r); if(row == null)継続; otapolicymodel = new otapolicymodel(); try {thread.currentthread()。sleep(1); } catch(arturnedexception e){e.printstacktrace(); } otapolicyModel.setPolicyid(System.CurrentTimemillis()); //(int c = 0; c <this.totalcells; c ++){cell cell = row.getCell(c); if(null!= cell){if(c == 0){otapolicymodel.setsource(cell.getStringCellValue()); // supplier} else if(c == 1){otapolicymodel.setvendee(cell.getStringCellvalue()); if(cell.getStringCellValue()== "all"){triptype = 0; } else if(cell.getStringCellValue()。equals( "single-way")){triptype = 10; } else if(cell.getStringCellValue()。equals( "Round Trip")){triptype = 20; } else if(cell.getStringCellValue()。equals( "単一ウェイ直接飛行")){triptype = 11; } else if(cell.getStringCellValue()。equals( "Round Trip")){triptype = 12; } else if(cell.getStringCellValue()。equals( "Round Trip")){triptype = 21; } else if(cell.getStringCellValue()。equals( "Round Trip")){triptype = 21; } else if(cell.getStringCellValue()。equals( "Round Trip")){triptype = 22; } otapolicymodel.settriptype(triptype); // itinerary type} else if(c == 3){otapolicymodel.setCarrier(cell.getStringCellValue()); //航空会社コード} else if(c == 4){otapolicymodel.getDepcity() city} else if(c == 5){otapolicymodel.setArrcity(cell.getStringCellValue()); // Landing City} else if(c == 6){otapolicymodel.setalebegindatel(new bigdecimal(cell.getnumericcellvalue())。setscale(0、bigdecimal.round_half_down).longvalue()); //販売開始日} else if(c == 7){otapolicymodel.setsaleenddatel(new bigdecimal(cell.getnumericcellvalue())。setscale(0、bigdecimal.round_half_down).longvalue()); //販売終了日} else if(c == 8){otapolicymodel.settravelbegindatel(new bigdecimal(cell.getnumericcellvalue())。setscale(0、bigdecimal.round_half_down).longvalue()); // travel start date} else if(c == 9){otapolicymodel.settravelenddatel(new bigdecimal(cell.getnumericcellvalue())。setscale(0、bigdecimal.round_half_down).longvalue()); //トラベル終了日} 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; } otapolicymodel.setCobintype(cabintype); // cadrift level} else if(c == 11){otapolicymodel.setfdtype(cell.getStringCellValue()。 otapolicymodel.setcabin(cell.getStringCellValue()); // cat} else if(c == 13){otapolicymodel.setPriceBegin(cell.getNumericCellValue()); //最小価格} else if(c == 14){otapolicymodel.getPriceEnd()価格} else if(c == 15){otapolicymodel.setlmoney(cell.getnumericcellvalue()); // money} else if(c == 16){otapolicymodel.setfpercent(cell.getnumericcellvalue()); otapolicymodel.setftpercent(cell.getnumericcellvalue()); // rebate} else if(c == 18){int carrierlimit = 2; if(cell.getStringCellValue()。equals( "yes")){carrierlimit = 1; } else if(cell.getStringCellValue()。equals( "no")){carrierlimit = 0; } else if(cell.getStringCellValue()。equals( "none")){carrierlimit = 2; } otapolicymodel.setCarrierLimit(carrierlimit); //請求書航空会社の制限} else if(c == 19){int Transport = 2; if(cell.getStringCellValue()。equals( "yes")){transport = 1; } else if(cell.getStringCellValue()。equals( "no")){Transport = 0; } else if(cell.getStringCellValue()。equals( "no")){Transport = 0; } else if(cell.getStringCellValue()。equals( "no")){Transport = 0; } else if(cell.getStringCellValue()。equals( "no")){Transport = 0; } else if(cell.getStringCellValue()。equals( "no")){Transport = 0; } else if(cell.getStringCellValue()。equals( "no")){Transport = 0; } else if(cell.getStringCellValue()。equals( "Unlimited")){Transport = 2; } otapolicyModel.setTransport(Transport); //サポートインターモーダルトランスポート} else if(c == 20){int sharedflight = 2; if(cell.getStringCellValue()。equals( "yes")){sharedflight = 1; } else if(cell.getStringCellValue()。equals( "no")){sharedflight = 0; } else if(cell.getStringCellValue()。equals( "none")){sharedflight = 2; } otapolicymodel.setsharedFlight(sharedflight); //サポート共有フライト} else if(c == 21){otapolicymodel.setpstatus()。 if(cell.getStringCellValue()。equals( "private")){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; } otapolicyModel.setFaretype(FareType); // Freight Type} else if(c == 23){otapolicymodel.setlimitprice(new bigdecimal(cell.getnumericcellvalue()) if(c == 24){int limittransit = 2; if(cell.getStringCellValue()。equals( "all")){limittransit = 2; } else if(cell.getStringCellValue()。equals( "apply")){limittransit = 0; } else if(cell.getStringCellValue()。 } otapolicymodel.setlimittransit(limittransit); // transition limit} else if(c == 25){otapolicymodel.setArrcity(cell.getStringCellValue()); // transition City} else if(c == 26){int limitnation = 2; if(cell.getStringCellValue()。equals( "all")){limitnation = 2; } else if(cell.getStringCellValue()。 } else if(cell.getStringCellValue()。equals( "limitnation = 1; } otapolicymodel.setlimitnation(limitnation); //国籍制限} else if(c == 27){otapolicymodel.setarrcity(cell.getStringCellvalue(); //国籍} else if(c == 28){otapolicymodel.setusername(cell.getStringcellvalue}; // customer otapolicymodellist.add(otapolicymodel); } otapolicymodellistを返します。 }}ツールクラスwdwutil.java
パッケージcom.flight.inter.otaadapter.commons.util;/*** 2016/12/29にling.zhangによって作成されました。 */ public class wdwutil {// @description:2003年のExcelであるかどうか、Return trueは2003年public static boolean isexcel2003(string filepath){return filepath.matches( "^。+/。(?i)(xls)$"); } //@説明:それが2007年のExcelであるかどうか、Return Trueは2007public Static Boolean isexcel2007(string filepath){return filepath.matches( "^。+//。(?i)(xlsx)$");}}}}注:利便性を読むために、上記のコードは最初に親の方法と次に子の方法で投稿されます。実際のコード編集では、子の方法は通常、最初に編集され、次に親法で編集されます。たとえば、上記は最初にツールクラスコードを編集し、サービスレイヤーコードを編集し、最後にコントローラーコードを編集する必要があります。
このようにして、プロセス全体が問題ありません。今すぐテストしてください
よりエキサイティングなコンテンツについては、詳細な調査と研究のために「スプリングアップロードと特別なトピックをダウンロード」をクリックしてください。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。