Naqueles dois dias, ajudei o professor a fazer um banco de dados e importar todos os dados das transações experimentais para o banco de dados. Mas eu não queria ficar em laboratório todos os dias. A atmosfera era muito deprimente, então pensei em ler os dados no Excel primeiro e trazê -los ao laboratório para importá -los.
Os dados acabaram sendo assim. Experimentos diferentes têm uma pasta especial. Existem pastas para diferentes classes sob a pasta do nome do experimento. A pasta de data da classe é armazenada nos dados do Excel para os experimentos em diferentes momentos. O Excel original não tinha aula e tempo. Agora você precisa adicionar essas informações como uma coluna lendo o nome do Excel e o nome da classe.
Abaixo está o código -fonte, Hehe, e uma janela de visualização também foi feita.
Classe Excelread:
importar java.awt.list; importar java.io.byteArrayoutputStream; importar java.io.file; importar java.io.fileInputStream; importar java.io.fileoutputStream; import java.io.ioException; importar java.io.outstream; importação; java.text.simpledEformat; importar java.util.ArrayList; importar org.apache.poi.hssf.usermodel.hsfcell; import org.apache.poi.hsf.usermodel.hssfdateutil; org.apache.poi.hssf.usermodel.hssfsheet; importar org.apache.poi.hssf.usermodel.hssfworkbook; import org.apache.poi.xssf.Usermodel.xsSsfell; importache.sach.xsf.xsfl; org.apache.poi.xssf.usermodel.xssfsheet; importar org.apache.poi.xssf.usermodel.xssfworkbook; public classe ExcelRead {string path; public; DecimalFormat ("0"); // Data de formatação da célula padrão String privada estática simpledateFormat sdf = new SimpleDateFormat ("AAAA-MM-DD HH: MM: SS"); // Número de formato Decimalformat estático privado nf = novo decimalformat ("0.00"); public static ArrayList <ArrayList <ject>> readExcel (arquivo de arquivo) {if (file == null) {return null;} if (file.getName (). endswith ("xlsx")) {// Processe ecxel2007 Return readExcel2007 (arquivo);}; @return armazenar o resultado de retorno no ArrayList, e a estrutura de armazenamento é semelhante a uma matriz de dois dígitos * lists.get (0) .get (0) significa 0 linhas e 0 colunas no Excel no passado */public static ArrayList <ArrayList <Becject>> ReadExcel2003 (arquivo de arquivo) {Try {ArrayList <Rlist <listlist <Teject>> ReadExcel2003 (arquivo de arquivo) {Try {ArrayList <listlist <listlist <frishList <jgeList>> ReadExcel2003 (arquivo de arquivo) {Try {ArrayList <listlist <listlist <frishList> ArrayList <ArrayList <Becut>> (); ArrayList <ject> Collist; hssfworkbook wb = new HSSFWorkbook (new FileInputStream (file)); hssfshet sheet = wb.getSheetat (0); hssfrow line; hssfcell; Sheet.getphysicalNumberOfRows (); else {rowcount ++;} para (int j = row.getfirstCellnum (); j <= row.getLastcellnum (); j ++) {Cell = row.getCell (j); if (Cell == NULL || Cell.getCeltype () == hsfCel.CELT_TYPE_TYPE_PLEMENTE_LANK) row.getLastcellnum ()) {// defende se é a última célula na linha colist.add ("");} continua;} switch (Cell.getCelltype ()) {case xssfcell.cell_type_string: //system.out.println(i + "Row" value = Cell.getStringCellValue (); Break; case xssfcell.cell_type_numeric: if ("@". Equals (Cell.getCellStyle (). getDataformatString ())) {value = df.format (Cell.getNumericCellValue ()); .getDataFormatString ())) {value = nf.Format (Cell.getNumericCellValue ());} else {value = sdf.format (hssfdateutil.getJavadate (Cell .getnumericCellValue (); + value.toString ()); Break; case xssfcell.cell_type_boolean: //system.out.println(i + "linha" + j + "coluna é tipo booleano"); value = boolean.valueof (Cell.getBooleaCellValue ()); Break; case xssfcell.cell_type_blank: //system.out.println(i + "line" + j + "coluna é em branco tipo"); value = ""; Break; padrão: //system.out.println(i + "ROW" + J + "A coluna é o tipo padrão"); value = Cell.ToString ();} // Switch final Collist.add (value);} // Switch de extremidade para j rowlist.add (coldist);} // termina para eu retorno rowlist;} catch (exceção e) {return null;}} filelist public) <Arraylist <justaL) {readxcel200; RowList = novo ArrayList <ArrayList <BECT>> (); ArrayList <BECT> Collist; XSSFWorkbook WB = new XSSFWorkbook (new FileInputStream (FILE); XSSFSHEET SHELLECT = WB.GetSheetat (0); XSSFROW ROW; XSFCELL; rowcount <Sheet.getphysicalNumberOfRows (); else {rowcount ++;} para (int j = row.getfirstCellnum (); j <= row.getLastcellnum (); j ++) {Cell = row.getCell (j); if (Cell == NULL || Cell.getCeltype () == hsfCel.CELT_TYPE_TYPE_PLEMENTE_LANK) row.getLastcellnum ()) {// julga se é a última célula na linha colist.add ("");} continua;} switch (Cell.getCelltype ()) {case xssfcell.cell_type_string: //system.out.println(i + "row" value = Cell.getStringCellValue (); Break; case xssfcell.cell_type_numeric: if ("@". Equals (Cell.getCellStyle (). getDataformatString ())) {value = df.format (Cell.getNumericCellValue ());}; .getDataFormatString ())) {value = nf.Format (Cell.getNumericCellValue ());} else {value = sdf.format (hssfdateutil.getJavadate (Cell .getnumericCellValue (); + value.toString ()); Break; case xssfcell.cell_type_boolean: //system.out.println(i + "linha" + j + "coluna é tipo booleano"); value = boolean.valueof (Cell.getBooleaCellValue ()); Break; case xssfcell.cell_type_blank: //system.out.println(i + "line" + j + "coluna é em branco tipo"); value = ""; Break; padrão: //system.out.println(i + "ROW" + J + "A coluna é o tipo padrão"); value = Cell.ToString ();} // Switch final Collist.add (value);} // termina para j rowlist.add (colist);} // termina para eu retorno rowlist;} // end para o retorno rowlist;} catch (excepção e) {system.out.println ("Exception"); retorno null; root = novo arquivo (filepath); arquivo [] arquivos = root.listfiles (); ArrayList filElist = new ArrayList (); para (arquivo de arquivo: arquivos) {if (file.isdirectory ()) {filelist.addall (getfiles (file.getabsolutepath ()));} else {string newpath = file.getabsolutepath (); if (newpath.contains ("transação")) {fillelist.ad; path3) {string filepath = path3; ArrayList filelels = getFiles (filepath); ArrayList <RrayList> resultall = new ArrayList <RrayList> (); para (int i = 0; i <fileList.size (); i ++) {string = (string) filelist.get (i); System.out.println (caminho); ArrayList <RrayList> resultado = Graph (caminho); String [] PATH2 = PATH.SPLIT ("///"); int num = resultado.get (0) .size (); ArrayList Result2 = New Arraylist (); 0; j <num; j ++) {resultado2.add (path2 [path2.Length-2]);} ArrayList Result3 = new ArrayList (); para (int j = 0; j <num; j ++) {resultado3.add (path2 [path2.Length-3); resultado.add (resultado (resultado); resultado;} else {for (int j = 0; j <resultado.size (); j ++) {for (int k = 0; k <resultado.get (j) .size (); k ++) {resultall.get (j) .add (resultado.get (j) .get (k));}}}}}}; WriteExcel (ArrayList <ArrayList> Resultado, String Path) {if (resultado == null) {return;} hssfworkbook wb = new hssfworkbook (); hssfsheet sheet = wb.creatheet ("Sheet1"); para (int i = 0; i <resultado.get (0). Sheet.Creterow (i); para (int j = 0; j <resultado.size (); j ++) {hssfcell célula = row.createCell ((curto) j); celular.setCellValue (resultado.get (j) .get (i) .ToString ());}} bytearAtTream OSS =. new) .ToString ();); e) {e.printStackTrace ();} byte [] content = os.tobytearray (); arquivo de arquivo = novo arquivo (caminho); // A localização do armazenamento após o arquivo do Excel é gerada. OutputStream fos = null; try {fos = new FileOutputStream (file); wb.write (fos); os.close (); fos.close ();} catch (exceção e) {e.printStackTrace ();}} public static decimalformat getdf () {retorno df;} {ExcelRead.df = df;} public static simpledEformatat getSdf () {return sdf;} public static void Setsdf (SimpledExformat sdf) {ExcelRead.sdf = sdf;} public estática decimal nf;} public static ArrayList <RrayList> Gráfico (String Path) {arquivo file = new File (caminho); ArrayList <ArrayList <ject>> resultado = ExcelRead.readExcel (arquivo); ArrayList <boun> preço = new ArrayList <ouble> (); ArrayList <String> Buylist = new ArrayList <String> (); // seqüência de comprador ArrayList <String> SeldList = new ArrayList <String> (); // seqüência de vendedor Arraylist <doun> vol = string = new ArrayList <woun> (); // volume de troca> ArrayList <String> (); ArrayList <String> shareid = new ArrayList <String> (); para (int i = 2; i <resultado.size (); i ++) {for (int j = 0; j <resultado.get (i) .size (); j ++) {// A coluna 5 representa o preço e a coluna 8 (ip). temp = (string) resultado.get (i) .get (j); shareid.add (temp);} if (j == 5) {// price.add ((string) resultado.get (i) .get (j)); string temp = (string) resultado.get (i). temp.split ("¥"); price. resultado.get (i) .get (j));} if (j == 2) {selllist.add ((string) resultado.get (i) .get (j));} if (j == 6) {vol.add (duplo.valueof ((string) result.get (i) .get (j)));} if (j == 4) {share.add ((string) resultado.get (i) .get (j));}}} ArrayList <RrayList> (); resultadoList.add (shareID); resultadoList.add (id); resultadoList.add (Buylist); resultadoList.add (SellList); resultadoList.Add (share); resultList.add (price); resultadolist.add (vol); result.d.d);ReadExcelbook (para janela de visualização):
importar java.awt.eventqueue; importar javax.swing.jfilechooser; importar javax.swing.jframe; importar javax.swing.grouplayout; importar javax.swing.jlabel; import javax.swing.GrouPlayout.alignment; import.jlabel; import.swing.grouPlayout.alignment; import.javaxswing; java.awt.event.actionListener; importar java.awt.event.actionEvent; importar java.io.file; public class ReadexcelBook {private jframe; */public static void main (string [] args) {eventQueue.invokelater (new runnable () {public void run () {try {readexcelBook window = new readexcelBookBook (); window.frame.setVisible (true);} catch (exceção e) {e.printStackTrace ();}; */public readExcelBook () {Initialize ();}/*** Inicialize o conteúdo do quadro. */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/U4ef {public void ActionPerformed (ActionEvent E) {jfileChooser jfc = new jfileChooser (); jfc.setFileSelectionMode (jfileChooser.files_and_directories); jfc.showdialog (novo jlabel (), "seleção"; file.getabsolutepath (); textfield.settext (path); excelread er = new Excelread (); er.readbook (path);}}); textfield = new jtextfield (); textfield.setColumns (10); jlabel lbldaxls = novo Jlabel ("/u5199/u5165/u4e86d/u76d8/u4e0b/u7684a.xls/u54c8"); grouPlayout grouPlayout = new GrouPlayout (estrutura.getContentPane (); grouplayout.createParallelGroup (alignment.leading) .addgroup (grouPlayout.createsequentialgroup () .addgap (26) .addgroup (grouPlayout.createParallelGoup (alinhamento.Leading) .AndComponent (LblaTaxlS) .AddCompCompCompCompCompCompCompConMpConMpConMpConMP) (lblaTaMPROTP). 295, grouPlayout.Preferred_Size) .AddComponent (Button)) .AddContAineRergap (113, Short.max_value))); .AddComponent (Button) .Addgap (18) .AddComponent (Textfield, GrouPlayout.Preferred_Size, GrouPlayout.Default_size, GrouPlayout.Preferred_Size) .AddGap (35) .AddConPONEN (LBLDAXLS) .DDCONT) ); estrutura.getContentPane (). Setlayout (GrouPlayout);}}Resultados em execução:
Resumir
O exposto acima é todo o conteúdo deste artigo sobre a redação e a redação do Java Excel Operation Sourching Sharing, espero que seja útil para todos. Os amigos interessados podem continuar se referindo aos tópicos relacionados a Java neste site. Se houver alguma falha, deixe uma mensagem para apontá -la. Obrigado amigos pelo seu apoio para este site!