Ces deux jours, j'ai aidé l'enseignant à créer une base de données et à importer toutes les données des transactions expérimentales dans la base de données. Mais je ne voulais pas rester en laboratoire tous les jours. L'atmosphère était trop déprimante, j'ai donc pensé à lire les données dans Excel d'abord et à les amener au laboratoire pour l'importer.
Les données se sont avérées comme ça. Différentes expériences ont un dossier spécial. Il existe des dossiers pour différentes classes sous le dossier du nom de l'expérience. Le dossier de date de classe est stocké dans les données Excel pour les expériences à différents moments. L'Excel d'origine n'avait pas de classe et de temps. Vous devez maintenant ajouter ces informations en tant que colonne en lisant le nom Excel et le nom de la classe.
Vous trouverez ci-dessous le code source, hehe, et une fenêtre de visualisation a également été réalisée.
Classe ExcelRead:
Importer java.awt.list; import java.io.bytearrayoutputStream; import java.io.file; import java.io.fileInputStream; import java.io.fileoututstream; import java.io.ioexception; java.util.arraylist; import org.apache.poi.hssf.usermodel.hssfcell; import org.apache.poi.hssf.usermodel.hssfdateutil; import org.apache.poi.hssf.UserModel.hssfrow; Import org.apache.poi.hssf.usermodel.hssfsheet; import org.apache.poi.hssf.usermodel.hssfworkBook; import org.apache.poi.xssf.UserModel.xssfcell; import org.apache.poi.xssf.Usermodel.xsfrow; org.apache.poi.xssf.usermodel.xssfsheet; import org.apache.poi.xssf.usermodel.xssfworkBook; public class excelread {String Path GetPath () {return Path;} public void SetPath (String Path) {this.path = path;} // format privil DECIMALFORMAT ("0"); // Date de formatage de la cellule par défaut String Private Static SimpledateFormat sdf = new SimpledateFormat ("yyyy-mm-dd hh: mm: ss"); // nombre de format privé static decimalformat nf = new decimalformat ("0,00"); public static arrayList <arrayList <objet>> readExcel (fichier file) {if (file == null) {return null;} if (file.getName (). Stockez le résultat de retour dans ArrayList, et la structure de stockage est similaire à un tableau à deux chiffres * lists.get (0) .get (0) signifie 0 lignes et 0 colonnes dans Excel dans le passé * / public static ArrayList <ArrayList <Bject>> readExcel2003 (fichier de fichier) {Try {ArrayList <ArrayList <Object>> RowList = new ArrayList <RARYListlist <objet> (); collist; hssfworkbook wb = new hssfworkbook (new FileInputStream (fichier)); hssfsheet sheet = wb.getSheetat (0); hssfrow row; hssfcell cell; objet valeur; pour (int i = sheet.getfirstrownum (), rowCount = 0; rowCount <ege.getPhysic sheet.getrow (i); collist = new ArrayList <Bject> (); if (row == null) {// lorsque le comportement de lecture est vide si (i! = sheet.getPhysicalNumberofrows ()) {// Défensez s'il s'agit de la dernière ligne RowList.Add (collist);} continue;} else {rowCount ++;} pour (int j = row.GirSTFURS <= row.getlastCellnum (); j ++) {cell = row.getCell (j); if (cell == null || cell.getCellType () == HssfCell.Cell_Type_Blank) {// lorsque la cellule est vide si (j! = Row.getlastCellNum ()) {// Débasse collist.add ("");} continue;} switch (Cell.getCellType ()) {case xssfcell.cell_type_string: //system.out.println(i + "row" + j + "colonne est un type de chaîne"); Value = Cell.getStringCellValue (); Break; case xssfcell.cell_type_numeric: if ("@". equal .getDataFormatString ()))) {value = nf.format (cell.getNumericCellValue ());} else {value = sdf.format (hssfdateutil.getjavadate (Cell .GetNumericCellValue ()));} // Collund Type: "I +" Row "+ J // +" // + value.toString ()); Break; case xssfcell.cell_type_boolean: //system.out.println(i + "row" + j + "colonne est booléen type"); valeur = boolean.valueof (Cell.getBoolEanCellValue ()); Break; case xssfcell.cell_type_blank: //system.out.println(i + "Row" + J + "La colonne est Blank Type"); Value = ""; Break; par défaut: //system.out.println(i + "Row" + J + "La colonne est par défaut"); Value = Cell.ToString ();} // End Switch Collist.Add (valeur);} // End Switch pour j rowList.add (collist);} // fin pour i return rowList;} catch (exception e) {return null;}} public static ArrayList <ArrayList <objet >> liseExcel2007 (file file) {Try {ArrayList <RARAYLIS ArrayList <ArrayList <Bject>> (); ArrayList <Bject> Collist; XSSFWorkBook WB = new XSSFWorkBook (new FileInputStream (fichier)); sheet.getPhysicalNumberOfrows (); i ++) {row = sheet.getRow (i); collist = new ArrayList <objet> (); if (row == null) {// lorsque le comportement de lecture est vide si c'est la dernière ligne RowList.addd (Collist);};}; else {rowCount ++;} for (int j = row.getFirstCellnum (); j <= row.getlastCellnum (); j ++) {cell = row.getCell (j); if (cell == null || cell.getCellType () == HSSFCELL.Cell_Type_Blank) {// quand la cellule est vide (j! row.getlastCellnum ()) {// juger s'il s'agit de la dernière cellule de la ligne collist.add ("");} continue;} switch (Cell.getCellType ()) {cass xssfcell.cell_type_string: //system.out.printlnnn. value = cell.getStringCellValue (); Break; case xssfcell.cell_type_numeric: if ("@". equal .getDataFormatString ()))) {value = nf.format (cell.getNumericCellValue ());} else {value = sdf.format (hssfdateutil.getjavadate (Cell .GetNumericCellValue ()));} // Collund Type: "I +" Row "+ J // +" // + value.toString ()); Break; case xssfcell.cell_type_boolean: //system.out.println(i + "row" + j + "colonne est booléen type"); valeur = boolean.valueof (Cell.getBoolEanCellValue ()); Break; case xssfcell.cell_type_blank: //system.out.println(i + "Row" + J + "La colonne est Blank Type"); Value = ""; Break; par défaut: //system.out.println(i + "Row" + J + "La colonne est par défaut"); Value = Cell.ToString ();} // end commutateur collist.add (valeur);} // end pour j rowlist.add (collist);} // fin pour i renvoie rowlist;} // end pour i return rowlist;} catch (exception e) {system.out.println ("exception"); File (filepath); file [] files = root.listFiles (); arrayList FileList = new ArrayList (); pour (fichier de fichier: fichiers) {if (file.isdirectory ()) {fileList.addall (getFiles (file.getAbsolupath ());} else {String newpath = file.getabsolupath (); if (newPath.ConTains ("transaction")) {fileList.add (newPath);}}} Readbook (String path3) {String FilePath = path3; arrayList FileList = GetFiles (filePath); ArrayList <RARYList> resultAll = new ArrayList <ArayList> (); pour (int i = 0; i <FileList.Size (); i ++) {String path = (string) fileList.get> Systems. Graph (path); string [] path2 = path.split ("////"); int num = result.get (0) .size (); arrayList result2 = new ArrayList (); for (int j = 0; j <num; j ++) {result2.add (path2 [path2.Lengthy 0; j <num; j ++) {result3.Add (path2 [path2.length-3]);} result.add (result2); result.add (result3); if (resultAll.Size () == 0) {resultall = result;} else {for (int j = 0; j <result.size (); j ++) {pour (int k = 0; k <result.get (j) .size (); k ++) {resultAll.get (j) .add (result.get (j) .get (k));}}}} writeExcel (resultAll, "d: /a.xls");} public static writeExcel (ArrayList <ArrayList> Result, string path) {if (result == null) {return;} hssfworkbook wb = new hssfworkbook (); hssfsheet sheet = wb.createet ("sheet1"); for (int i = 0; i <result.get (0) .size (); i ++) {hssfrow row = sheet.creater (i); pour (int j = 0; j <result.size (); j ++) {hssfcell cell = row.createCell ((short) j); cell.setCellValue (result.get (j) .get (i) .toString ());}} bytearrayoutPutStream OS = new byTayoutStream (); Try {wb.write (OS);}}}}}}}; (IoException e) {e.printStackTrace ();} byte [] contenu = os.toByTearray (); fichier file = new File (path); // L'emplacement du stockage après le fichier Excel est généré. OutputStream fos = null; try {fos = new FileOutputStream (fichier); wb.write (fos); os.close (); fos.close ();} catch (exception e) {e.printStackTrace ();}} public static static stati {ExcelRead.df = df;} public static SimpledateFormat getDf () {return sdf;} public static void setsdf (SimpledateFormat sdf) {excelread.sdf = sdf;} public static decimalformat getnf () {return nf;} public static sted setnf (decimalformat nf) {ExcelRead.nf = nf;} public static arrayList <ArrayList> graphique (String path) {file file = new File (path); ArrayList <RARYList >> Result = excelRead.readExcel (file); ArrayList <WOBD> Price = new ArrayList <DonD> (); // prime séquence ArrayList <String> Time = Time = Time = Time = Time = TIME INFACT ArrayList <string> buyList = new ArrayList <string> (); // séquence d'acheteur ArrayList <string> sellList = new ArrayList <String> (); // Sequence Vendre ArrayList <DIBLE> Vol = new ArrayList <Don> (); // Trading Volume ArrayList <string> Share = Share = New ArrayList <string> (); // Stock Name ArrayList <string> ArrayList <string> (); arrayList <string> shareId = new ArrayList <string> (); pour (int i = 2; i <result.size (); i ++) {for (int j = 0; j <result.get (i) .size (); j ++) {// colonne 5 représente le prix, et la colonne 8 représente le temps if (j == 0) {String temp = (String) result.get (i) .get (j); id.add (temp);} if (j ==) (String) result.get (i) .get (j); shareId.add (temp);} if (j == 5) {// price.add ((string) result.get (i) .get (j)); string temp = (string) result.get (i) .get (j); string [] units = temp.split ("¥"); prix.add (double.valueof (unités [1]));} if (j == 7) {String temp = (string) result.get (i) .get (j); time.add (temp); // time.add ((string) result.get (i) .get (j));} if (j == 1) {buyList.add (String (j));} if (j == 1) {buyList.add (String (j));} if (j == 1) {buyList.add (String (j));} if (j == 1) {buyList.add (String (j));} result.get (i) .get (j));} if (j == 2) {selllist.add ((string) result.get (i) .get (j));} if (j == 6) {vol.add (double.valueof ((string) result.get (i) .get (j)));} if (j == 4) {share.add ((string) result.get (i) .get (j));}}} arrayList <ArrayList> ResultList = newtlist = newtLe ArrayList <ArayList> (); resultList.add (ShareId); resultList.add (id); resultList.add (BuyList); resultList.add (sellList); resultList.add (Share); resultList.add (Price)ReadExcelBook (pour la fenêtre de visualisation):
import java.awt.eventqueue; import javax.swing.jfilechooser; import javax.swing.jframe; import javax.swing.grouplayout; import javax.swing.jlabel; import javax.swing.grouplayout.alignment; import javax.swing.jbutton; import javax.swing.jtext java.awt.event.actionListener; import java.awt.event.actionEvent; import java.io.file; public class readExcelbook {private jframe frame; private jTextfield textfield; / ** * lancez l'application. * / public static void main (String [] args) {eventQueue.invokelater (new Runnable () {public void run () {try {readExcelBook windows = new ReadExcelBook (); window.frame.setVisible (true);} catch (exception e) {e.printStackTrace ();}}});} / ** * Créer la demande. * / public readExcelBook () {initialize ();} / ** * Initialisez le contenu du cadre. * / private void initialize () {frame = new JFrame (); frame.setbounds (100, 100, 450, 300); frame.setDefaultCloseOperation (jframe.exit_on_close); Jbutton Button = new JBUTTON ("/ U9009 / U62E9 / U6587 / U4EF6"); Button.AddActionLester (New Actionner () {UNTOR void ActionPerformed (ActionEvent e) {jFileChoOSer jfc = new JFileChoOser (); jfc.SetFilesElectionMode (jFileChoOser.Files_and_Directries); Jfc.showDialog (new JLABEL (), "SELECT"); file file = jfc.getSelectedFile ();) file.getabsolutepath (); textField.setText (path); excelread er = new ExcelRead (); er.readbook (path);}}); textfield = new JTextField (); textfield.setColumns (10); jlabel lbldaxls = new JLabel ("/ u5199 / u5165 / u4e86d / u76d8 / u4e0b / u7684a.xls / u54c8"); grouplayout grouplayout = new Grouplayout (frame.getContentPane ()); grouplayout.sethorizontalgroup (Frame.GetContentPane ()); Grouplayout.SethorizontalGroup ( Grouplayout.CreateParalleGroup (Alignment.Leading) .AddGroup (GrouplayOut.CreateSquentialGroup () .Addgap (26) .AddGroup (Grouplayout.CreateParalleGroup (Alignment.Leading) .AdddComponent (LBLDAXLS). Grouplayout.Preferred_Size) .AddComponent (Button)) .AddContainergap (113, short.max_value))); Grouplayout.SetVerticalGroup (Grouplayout.CreateParalleGroup (Alignment.Leading) .AddGroup (Grouplayout.CreateEqualiengrou .Addgap (18) .AddComponent (TextField, Grouplayout.Preferred_Size, Grouplayout.Default_Size, Grouplayout.Preferred_Size) .Addgap (35) .AddComponent (LBLDAXLS) .AddContainGap (119, Short.Max_Value))). ); frame.getContentPane (). SetLayout (Grouplayout);}}Résultats en cours:
Résumer
Ce qui précède est tout le contenu de cet article sur l'écriture Java et l'écriture du partage de code source d'opération Excel, j'espère que cela sera utile à tout le monde. Les amis intéressés peuvent continuer à se référer aux sujets liés à Java sur ce site Web. S'il y a des lacunes, veuillez laisser un message pour le signaler. Merci vos amis pour votre soutien pour ce site!