easyexcel 讀寫demo


 1 <dependencies>
 2         <dependency>
 3             <groupId>com.alibaba</groupId>
 4             <artifactId>easyexcel</artifactId>
 5             <version>1.1.1</version>
 6         </dependency>
 7 
 8         <dependency>
 9             <groupId>junit</groupId>
10             <artifactId>junit</artifactId>
11             <version>4.9</version>
12         </dependency>
13 
14         <!-- jdbc -->
15         <dependency>
16             <groupId>commons-dbutils</groupId>
17             <artifactId>commons-dbutils</artifactId>
18             <version>1.7</version>
19         </dependency>
20 
21         <dependency>
22             <groupId>com.mchange</groupId>
23             <artifactId>c3p0</artifactId>
24             <version>0.9.5.2</version>
25         </dependency>
26 
27         <dependency>
28             <groupId>mysql</groupId>
29             <artifactId>mysql-connector-java</artifactId>
30             <version>5.1.40</version>
31         </dependency>
32 
33 </dependencies>

工具類

 1 package cn.tele.demo;
 2 
 3 import java.sql.Connection;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.sql.Statement;
 7 import javax.sql.DataSource;
 8 import com.mchange.v2.c3p0.ComboPooledDataSource;
 9 
10 /** 
11  *
12  *@author Tele
13  *
14  */
15 
16 public class JdbcUtils {
17     private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
18     
19     
20     public static Connection getConnection() throws SQLException {
21         return dataSource.getConnection();
22     }
23     
24     public static DataSource getDS() {
25         return dataSource;
26     }
27     
28     // 關閉數據庫連接
29     public static void close(ResultSet rs, Statement stat, Connection conn) {
30             try {
31                 if (rs != null)
32                     rs.close();
33                 if (stat != null)
34                     stat.close();
35                 if (conn != null)
36                     conn.close();
37             } catch (SQLException e) {
38                 e.printStackTrace();
39             }
40             
41      }
42     
43 }
View Code

實體類(模型)

 1 package cn.tele.demo;
 2 
 3 import com.alibaba.excel.annotation.ExcelProperty;
 4 import com.alibaba.excel.metadata.BaseRowModel;
 5 
 6 /** 
 7  *
 8  *@author Tele
 9  *
10  */
11 
12 public class Student extends BaseRowModel{
13     @ExcelProperty(value="學號",index=0)
14     private Integer id;
15     
16     @ExcelProperty(value= {"姓名","name","xxx","xxx"},index=1)
17     private String name;
18     
19     @ExcelProperty(value="指導老師",index=2)
20     private String teacher;
21 
22     public Integer getId() {
23         return id;
24     }
25 
26     public void setId(Integer id) {
27         this.id = id;
28     }
29 
30     public String getName() {
31         return name;
32     }
33 
34     public void setName(String name) {
35         this.name = name;
36     }
37 
38     public String getTeacher() {
39         return teacher;
40     }
41 
42     public void setTeacher(String teacher) {
43         this.teacher = teacher;
44     }
45 
46     @Override
47     public String toString() {
48         return "Student [id=" + id + ", name=" + name + ", teacher=" + teacher + "]";
49     }
50 }
View Code

監聽器

 1 package cn.tele.demo;
 2 
 3 import java.sql.SQLException;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 import org.apache.commons.dbutils.QueryRunner;
 8 
 9 import com.alibaba.excel.context.AnalysisContext;
10 import com.alibaba.excel.event.AnalysisEventListener;
11 
12 /** 
13  *
14  *@author Tele
15  *
16  */
17 
18 public class ExcelListener extends AnalysisEventListener<Student>{
19 
20     //自定義用於暫時存儲data。
21     //可以通過實例獲取該值
22     private List<Student> datas = new ArrayList<Student>();
23     
24     //每解析一行調用一次invoke方法
25     public void invoke(Student object, AnalysisContext context) {
26         System.out.println("當前行:"+context.getCurrentRowNum());
27         System.out.println(object);
28         datas.add(object);//數據存儲到list,供批量處理,或后續自己業務邏輯處理。
29         doSomething(datas);//根據自己業務做處理
30     }
31     
32     private void doSomething(List<Student> list) {
33       
34     }
35     
36     //解析結束后自動調用
37     public void doAfterAllAnalysed(AnalysisContext context) {
38        // datas.clear();//解析結束銷毀不用的資源
39           //1、入庫調用接口
40         QueryRunner runner = new  QueryRunner(JdbcUtils.getDS());
41         String sql = "insert into student values(?,?,?)";
42         for(Student student:datas) {
43             try {
44                 runner.update(sql, new Object[] {student.getId(),student.getName(),student.getTeacher()});
45             } catch (SQLException e) {
46                 e.printStackTrace();
47             }
48         }
49         
50         System.out.println("數據更新完成");
51         try {
52             JdbcUtils.close(null,null,JdbcUtils.getConnection());
53         } catch (SQLException e) {
54             e.printStackTrace();
55         }
56         
57     }
58     public List<Student> getDatas() {
59         return datas;
60     }
61     public void setDatas(List<Student> datas) {
62         this.datas = datas;
63     }
64 
65 }
View Code

Demo

 1 package cn.tele.demo;  2 
 3 import java.io.File;  4 import java.io.FileInputStream;  5 import java.io.FileNotFoundException;  6 import java.io.FileOutputStream;  7 import java.io.IOException;  8 import java.io.InputStream;  9 import java.io.OutputStream;  10 import java.sql.SQLException;  11 import java.util.List;  12 
 13 import org.apache.commons.dbutils.QueryRunner;  14 import org.apache.commons.dbutils.handlers.BeanHandler;  15 import org.apache.commons.dbutils.handlers.BeanListHandler;  16 import org.junit.Test;  17 
 18 import com.alibaba.excel.ExcelReader;  19 import com.alibaba.excel.ExcelWriter;  20 import com.alibaba.excel.metadata.Sheet;  21 import com.alibaba.excel.support.ExcelTypeEnum;  22 
 23 /**
 24  * 讀取Excel  25  *  26  * @author Tele  27  *  28  */
 29 
 30 public class Demo {  31 
 32     /**
 33  * 讀取excel並插入mysql中 sheet第一個參數為sheetNo代表sheet的編號,第二個參數表示從第幾行開始讀,最小是1, new  34  * Sheet(1,0,Student.class)發現無輸出結果  35  *  36  * @throws FileNotFoundException  37      */
 38     @SuppressWarnings("deprecation")  39  @Test  40     public void readExcel() throws FileNotFoundException {  41         InputStream inputStream = new FileInputStream("d:/excelTest/test.xlsx");  42         try {  43             // 解析每行結果在listener中處理
 44             ExcelListener listener = new ExcelListener();  45 
 46             ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);  47             excelReader.read(new Sheet(1, 1, Student.class));  48         } catch (Exception e) {  49 
 50         } finally {  51             try {  52  inputStream.close();  53             } catch (IOException e) {  54  e.printStackTrace();  55  }  56  }  57  }  58 
 59     /**
 60  * 查詢測試  61      */
 62  @Test  63     public void queryByGroup() {  64         QueryRunner runner = new QueryRunner(JdbcUtils.getDS());  65         String sql = "SELECT * from student group by teacher,id";  66         try {  67             List<Student> query = runner.query(sql, new BeanListHandler<Student>(Student.class));  68             for (Student student : query) {  69                 System.out.println(student.getName() + "----" + student.getTeacher());  70  }  71 
 72         } catch (SQLException e) {  73  e.printStackTrace();  74  }  75  }  76 
 77     /**
 78  * 將查詢結果寫出到excel中 在寫excel的過程中,含有模型的寫入,對於sheet的第二個參數是忽略的,全部從左側第一行進行讀寫  79      */
 80  @Test  81     public void writeExcel() {  82         try {  83             OutputStream os = new FileOutputStream(new File("d:/excelTest/new.xlsx"));  84             ExcelWriter writer = new ExcelWriter(os, ExcelTypeEnum.XLSX, true);  85 
 86             // 2代表sheetNo,不可以重復,如果兩個sheet的sheetNo相同則輸出時只會有一個sheet
 87             Sheet sheet1 = new Sheet(1, 5, Student.class);  88             sheet1.setSheetName("第一個sheet");  89 
 90             Sheet sheet2 = new Sheet(2, 1, Student.class);  91             sheet2.setSheetName("第二個sheet");  92 
 93             QueryRunner runner = new QueryRunner(JdbcUtils.getDS());  94             String sql = "SELECT * from student group by teacher,id";  95 
 96             List<Student> result = runner.query(sql, new BeanListHandler<Student>(Student.class));  97  writer.write(result, sheet1);  98             // writer.write(result,sheet2);
 99 
100  writer.finish(); 101             System.out.println("數據已寫出"); 102         } catch (FileNotFoundException e) { 103  e.printStackTrace(); 104         } catch (SQLException e) { 105  e.printStackTrace(); 106  } 107 
108  } 109 
110 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM