Estos dos días, ayudé al maestro a hacer una base de datos e importar todos los datos de las transacciones experimentales en la base de datos. Pero no quería quedarme en el laboratorio todos los días. La atmósfera era demasiado deprimente, así que pensé en leer los datos en Excel primero y llevarlos al laboratorio para importarlos.
Los datos resultaron ser así. Diferentes experimentos tienen una carpeta especial. Hay carpetas para diferentes clases en la carpeta del nombre del experimento. La carpeta de fecha de clase se almacena en los datos de Excel para los experimentos en diferentes momentos. El Excel original no tenía clase y tiempo. Ahora debe agregar esta información como una columna leyendo el nombre de Excel y el nombre de clase.
A continuación se muestra el código fuente, jeje y una ventana de visualización.
Clase Excelread:
import java.awt.list; import java.io.bytearRayOutputStream; import java.io.file; import java.io.fileinputStream; import java.io.fileutputStream; import java.io.ioexception; import java.io.outputStream; import java.text.decimalformat; importar; import java.text.simpledateFormat; import java.util.arrayList; import org.apache.poi.hssf.usermodel.hssfcell; import org.apache.poi.hssf.usermodel.hsssfdateutil; import org.apache.poi.hssf.usmodel org.apache.poi.hssf.usermodel.hssfsheet; import org.apache.poi.hssf.usermodel.hssfworkbook; importar org.apache.poi.xssf.usermodel.xsfcell; import org.apache.poi.xssf.usermodel.xssfsheet; import org.apache.poi.xssf.usermodel.xssfworkbook; public class Excelread {String Path; public String String getPath () {return ruta;} public void setPath (string ruta) DecimalFormat ("0"); // Fecha de formato de celda predeterminada Cadena privada static simpledateFormat sdf = new SimpleDateFormat ("yyyyy-mm-dd hh: mm: ss"); // número de formato decimalformat estático privado nf = new DecimalFormat ("0.00"); public static arrayList <ArrayList <Sect>> readExcel (archivo file) {if (file == null) {return null;} if (file.getName (). endswith ("xlsx")) {// proceso ecxel2007 return readExcel2007 (file);} else {// process ecxel2003 return readexcel2003 (File/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *; @return almacena el resultado de retorno en ArrayList, y la estructura de almacenamiento es similar a una matriz de dos dígitos * lists.get (0) .get (0) significa 0 filas y 0 columnas en Excel en el pasado */public static arrayList <ArrayList <sect>> ReadExcel2003 (archivo de archivo) {try {arrayList <arraylist <pectus>> rowList = newList = newList = newList = newList = newList = newList = newList = newList = NewList = newList = newexcel ArrayList <ArrayList <Sect> (); ArrayList <ject> collist; hssfworkbook wb = new hssfworkbook (new FileInputStream (file)); HSSFSheet sheet = wb.getSheetat (0); hssfrow row; hssfcell celular; valor de objeto; for (int i = sheet.getFirstrownum (), rowCount = 0; 0; 0; 0; 0; 0; 0; sheet.getPhySicalNumberOfRows (); else {rowCount ++;} for (int j = row.getFirstCellNum (); j <= row.getLastCellNum (); j ++) {celular = row.getCell (j); if (celular == null || cell.getCellType () == HSSFCELL.CELL_TYPE_BLANK) Row.getLastCellNum ()) {// Defiende si es la última celda en la fila Collist.Add ("");} continuar;} switch (celular.getCellType ()) {case xssfcell.cell_type_string: //system.out.println(i + "file" + j + "columna es un tipo de cadena");;;;; value = cell.getStringCellValue (); break; case xssfcell.cell_type_numeric: if ("@". Equals (cell.getCellStyle (). getDataFormatString ())) {valor = df.Format (cell.getNumericCellValue ();); .getDataFormAtString ())) {value = nf.format (cell.getNumericCellValue ());} else {value = sdf.format (hssfdateUtil.getJavadate (celular .getNumericCellValue ());} // system.Println (i + "row" + j // + "columna type; + valor.toString ()); break; case xssfcell.cell_type_boolean: //system.out.println(i + "fila" + j + "columna es tipo boolean"); valor = boolean.valueOf (cell.getBooleAnCellValue ()); break; case xssfcell.cell_type_blank: //system.out.println(i + "fila" + j + "columna es tipo en blanco"); valor = ""; ruptura; default: //system.out.println(i + "fila" + j + "columna es tipo predeterminado"); value = cell.toString();}// end switch colList.add(value);}// end switch for j rowList.add(colList);}//end for i return rowList;}catch(Exception e){return null;}}public static ArrayList<ArrayList<Object>> readExcel2007(File file){try{ArrayList<ArrayList<Object>> RowList = new ArrayList <ArrayList <SPEt> (); ArrayList <ject> collist; xssfworkbook wb = new XSSFWorkBook (new FileInputStream (file)); XSSFSEET hoja = wb.getSheetat (0); XSSFROW; RowCount <sheet.getPhySicalNumberOfRows (); i ++) {row = sheet.getrow (i); collist = new ArrayList <SPET> (); if (Row == NULL) {// Cuando el comportamiento de lectura está vacío if (i! = sheet.getPhySicalNumberOfRows () {// JUEG else {rowCount ++;} for (int j = row.getFirstCellNum (); j <= row.getLastCellNum (); j ++) {celular = row.getCell (j); if (celular == null || cell.getCellType () == HSSFCELL.CELL_TYPE_BLANK) Row.getLastCellNum ()) {// juzga si es la última celda en la fila Collist.Add ("");} continuar;} switch (celular.getCellType ()) {case xssfcell.cell_type_string: //system.out.println(i + "file" + j + "columna es un tipo de cadena");;;;; value = cell.getStringCellValue (); break; case xssfcell.cell_type_numeric: if ("@". Equals (cell.getCellStyle (). getDataFormatString ())) {valor = df.format (cell.getNumericCellValue ();); .getDataFormAtString ())) {value = nf.format (cell.getNumericCellValue ());} else {value = sdf.format (hssfdateUtil.getJavadate (celular .getNumericCellValue ());} // system.Println (i + "row" + j // + "columna type; + valor.toString ()); break; case xssfcell.cell_type_boolean: //system.out.println(i + "fila" + j + "columna es tipo boolean"); valor = boolean.valueOf (cell.getBooleAnCellValue ()); break; case xssfcell.cell_type_blank: //system.out.println(i + "fila" + j + "columna es tipo en blanco"); valor = ""; ruptura; default: //system.out.println(i + "fila" + j + "columna es tipo predeterminado"); value = cell.ToString ();} // end switch collist.add (valor);} // finalizar para j rowList.add (collist);} // final para i return rowList;} // end para i return rowList;} catch (excepción e) {system.out.println ("excepción"); return null;}} public static static shatlist root = new File (FilePath); file [] files = root.listfiles (); ArrayList fileList = new ArrayList (); para (archivo archivo: archivos) {if (file.isDirectory ()) {fileList.addall (getFiles (file.getabsolutePath ());} else {String newpath = file.getAbSolutePath (); if (newpath.Contains ("transacción")) {fileList.add (newpath);}}}}}} Readbook (String Path3) {String filePath = path3; ArrayList fileList = getFiles (filePath); ArrayList <RARAYLIST> resultall = new ArrayList <RARAYLIST> (); for (int i = 0; i <fileList.size (); i ++) {string path = (String) fileList.get (i); System.out.println (ruta); ArrayList <ArrayList> result = 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.length-2]);} ArrayList result3 = new ArrayList (); for (int j = 0; j <num; j ++) {result3.Add (path2 [path2.length-3]);} result.Add (result2); result.add (result3); if (() == 0) resultado;} else {for (int j = 0; j <result.size (); j ++) {for (int k = 0; k <result.get (j) .size (); k ++) {resultall.get (j) .Add (resultado.get (j) .get (k));}}}} writeExcel (resultall, "d: /a.xls");} writeExcel (ArrayList <RArrayList> resultado, string ruta) {if (result == null) {return;} hssfworkbook wb = new hssfworkbook (); hssfsheet sheet = wb.createSheetet ("sheet1"); for (int i = 0; i <sult.get (0) .size (); i ++)) hoja.createrow (i); for (int j = 0; j <result.size (); j ++) {hssfcell cell = row.createCell ((short) j); cell.setCellValue (result.get (j) .get (i) .ToString ());}} byTearRautputPutPutStream OS = new ByTearRaRyReam (); Try {WB.WRWRITI e) {E.PrintStackTrace ();} byte [] content = OS.TobyTearray (); archivo de archivo = nuevo archivo (ruta); // La ubicación de almacenamiento después de generar el archivo Excel. OutputStream fos = null; try {fos = new FileOutputStream (file); wb.write (fos); os.close (); fos.close ();} capt (excepción e) {e.printstackTrace ();}} public staticformat getDf () {return df;} public setdff (decimalformat df) {Excelread.df = df;} public static SimpledateFormat getSdf () {return sdf;} public static void setSdf (simpledateFormat sdf) {Excelread.sdf = sdf;} public staticSalFormat getNf () {return nf;} public statnf (decimalformat nf) {{{nf) nf;} public static arrayList <RARAYLIST> GRAPH (string path) {file file = new File (Path); ArrayList <ArrayList <ject>> result = Excelread.read.ReadExcel (file); ArrayList <Double> Price = New ArrayList <Wouble> (); // Price secuence ArrayList <Turte> TIME = new ArrayListSlist; ArrayList <String> buyList = new ArrayList <String> (); // Comprador secuencia ArrayList <String> sellList = new ArrayList <String> (); // SECULACIÓN DEL VENDEDOR SECURSE ARAYLIST <Oblo> vol = new ArrayList <Souble> (); // Comercio de Volumen de comercio ArrayList <String> share = new ArrayList <String> (); // stock name arrayList ArrayList <String> (); ArrayList <String> shareId = new ArrayList <String> (); for (int i = 2; i <result.size (); i ++) {for (int j = 0; j <result.get (i) .size (); j ++) {// columna 5 representa el precio, y la columna 8 representa el tiempo if (j == 0) {string temp = (string) result.get (i) .get (j); id.add (temp);} si (j == 3) (String) result.get (i) .get (j); shareId.add (temp);} if (j == 5) {// precio.add ((string) result.get (i) .get (j)); string temp = (string) result.get (i) .get (j); string [] units = temp.split ("¥"); Price.Add (double.ValueOf (units [1]));} if (j == 7) {String temp = (string) result.get (i) .get (j); time.Add (TEMP); // time.add ((string) result.get (i) .get (j)); result.get (i) .get (j));} if (j == 2) {SellIlst.Add ((String) result.get (i) .get (j));} if (j == 6) {vol.add (doble.ValueOf (((String) result.get (i) .get (j)));} if (j == 4) {share.add (((string) result.get (i) .get (j));}} arraylist <ArrayList> resultlist = neweN ArrayList <RARAYLIST> (); resultList.Add (shareId); resultList.Add (id); resultList.Add (buyList); resultList.Add (SellList); resultList.Add (share); resultList.Add (precio); resultList.add (vol); resultList.Add (Time); regreso resultado;}}}}ReadExcelbook (para la ventana de visualización):
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.swing.swing.swing; import. java.awt.event.actionListener; import java.awt.event.actionEvent; import java.io.file; public class ReadExcelBook {private jFrame Frame; private jtextfield textield;/*** Inicie la aplicación. */public static void main (string [] args) {eventQueue.invokElater (new runnable () {public void run () {try {readExcelbook Window = new ReadExcelBook (); Window.frame.SetVisible (true);} Catch (Exception e) {E.PrintStackArtace ();}}}});}/*** Crear la aplicación. */public readExcelbook () {inicialize ();}/*** Inicializa el contenido del marco. */private void inicialize () {frame = new jframe (); frame.setBounds (100, 100, 450, 300); frame.setDefaultCloseOperation (jframe.exit_on_close); jButton Button = new JButton ("/U9009/U62E9/U6587/U4EF6"); Button. {public void ActionperFormed (ActionEvent E) {jfilechooser jfc = new jfileCooser (); jfc.SetFileSelectionMode (jfilechooser.files_and_directories); jfc.showDialog (neow jlabel (), "select"); archivo = 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 ( GrouplaYout.CreateParAllelGroup (alignment.leading) .AddGroup (GrouplaYout.CreateSequentialGroup () .addgap (26) .addGroup (grouplaYOut.CreateParallelGroup (aligns.leading) .AddComponent (LblDaxls) .addComponent (textField, de campo. GrouplaYout.Preferred_Size, 295, GrouplaYout.Preferred_Size) .AddComponent (Button)) .addContainGap (113, Short.Max_Value)); GrouplaYout.SetVerTicalGroup (GrouplaYout.CreateParAlLelgroup (alineación.leading) .addGroup (GrouplaYout.CreateSequentialGroup () .addgap (31) .addComonent (botón) .addgap (18) .addComponent (textField, grouplaYout.preferred_size, grouplaYout.default_size, grouplaYout.prefered_size .addgap (35) .addComponent (lBlDaxls) .addContainGap (119, short.max_value))); frame.getContentPane (). SetLayout (GrouplaYout);}}Resultados de ejecución:
Resumir
Lo anterior es todo el contenido de este artículo sobre la escritura de Java y la escritura de Excel Operation Code Code Compartir, espero que sea útil para todos. Los amigos interesados pueden continuar referiéndose a los temas relacionados con Java en este sitio web. Si hay alguna deficiencia, deje un mensaje para señalarlo. ¡Gracias amigos por su apoyo para este sitio!