java讀取excel檔案資料匯入mysql資料庫

來源:互聯網
上載者:User

標籤:string   nbsp   擷取   buffer   maven倉庫   支援   pac   util   資料庫表   

這是我來公司的第二周的一個小學習任務,下面是實現過程:

 

1.建立maven工程(方便管理jar包)


在pom.xml匯入 jxl,mysql-connector 依賴

 

可以在maven倉庫搜尋

2.建立資料庫連接類,資料庫對應實體類

2.編寫資料庫表對應的實體類 ,get、set方法等

3.下面是編寫讀取excel檔案的類 ,和運行主類

 

package service;import java.io.File;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import jxl.Sheet;import jxl.Workbook;import excel.DB;import excel.Student;public class StudentService {    /**     * 查詢Student表中所有的資料     * @return      */    public static List<Student> getAllByDb(){        List<Student> list=new ArrayList<Student>();        try {            DB db=new DB();            String sql="select * from student";            ResultSet rs= db.Search(sql, null);            while (rs.next()) {                int id=rs.getInt("id");                String s_name=rs.getString("s_name");                String age=rs.getString("age");                String address=rs.getString("address");                                list.add(new Student(id, s_name, age,address));            }                    } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return list;    }        /**     * 查詢指定目錄中試算表中所有的資料     * @param file 檔案完整路徑     * @return     */    public static List<Student> getAllByExcel(String file){        List<Student> list=new ArrayList<Student>();        try {            Workbook rwb=Workbook.getWorkbook(new File("F:\\student.xls"));            Sheet rs=rwb.getSheet(0);//表            int clos=rs.getColumns();//得到所有的列            int rows=rs.getRows();//得到所有的行                        System.out.println("表的列數:"+clos+" 表的行數:"+rows);            for (int i = 1; i < rows; i++) {                for (int j = 0; j < clos; j++) {                    //第一個是列數,第二個是行數                    String id=rs.getCell(j++, i).getContents();//預設最左邊編號也算一列 所以這裡得j++                                       String s_name=rs.getCell(j++, i).getContents();                    String age=rs.getCell(j++, i).getContents();                    String address=rs.getCell(j++, i).getContents();                                        System.out.println("id:"+id+" name:"+s_name+" sex:"+age+" address:"+address);                    list.add(new Student(Integer.parseInt(id), s_name,age,address));                }            }        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }         return list;            }        /**     * 通過Id判斷是否存在     * @param id     * @return     */    public static boolean isExist(int id){        try {            DB db=new DB();            ResultSet rs=db.Search("select * from student where id=?", new String[]{id+""});            if (rs.next()) {                return true;            }        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return false;    }        public static void main(String[] args) {                        System.out.println(isExist(1));            }    }

運行主類:

package service;import java.util.List;import excel.DB;import excel.Student;public class TestExcelToDb {    public static void main(String[] args) {        //得到表格中所有的資料        List<Student> listExcel=StudentService.getAllByExcel("F:\\student.xls");                                      DB db=new DB();                for (Student student : listExcel) {            int id=student.getId();            System.out.println(id);            if (!StudentService.isExist(id)) {                //不存在就添加                String sql="insert into student (id,s_name,age,address) values(?,?,?,?)";                String[] str=new String[]{id+"",student.getS_name(),student.getAge(),student.getAddress()+""};                db.AddU(sql, str);            }else {                //存在就更新                String sql="update student set s_name=?,age=?,address=? where id=?";                String[] str=new String[]{student.getS_name(),student.getAge(),student.getAddress()+"",id+""};                db.AddU(sql, str);            }        }    }}

資料庫:[Excel資料表頭要與資料庫欄位對應]

 

總結:以上是使用了 jxl實現的讀取excel檔案內容,並且將資料傳到mysql,缺陷是:jxl僅支援EXCEL2003。

   要改進相容2003和2007需要使用pol,要匯入pol相關jar包

    pol 裡面有有兩個類是處理Excel2003 和Excel2007的

    HSSF-----2003,XSSF-----2007

下面是通過讀取檔案名稱判斷該檔案類型是03還是07的類方法。因為03和07很顯然在檔案尾碼名就存在區別

/**     * 對外提供讀取excel 的方法     * */    public static List<String> readExcel(File file) throws IOException {        String fileName = file.getName();        List<String> list = new ArrayList<String>();        //根據其名稱擷取尾碼        String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName                .substring(fileName.lastIndexOf(".") + 1);        String[][] result = null;        if ("xls".equals(extension)) {            result = read2003Excel(file);        } else if ("xlsx".equals(extension)) {            result = read2007Excel(file);        } else {            throw new IOException("不支援的檔案類型");        }        int rowLength = result.length;                for (int i = 0; i < rowLength; i++) {            StringBuffer sb = new StringBuffer();            for (int j = 0; j < result[i].length; j++) {                if(!"".equals(result[i][j]) && result[i][j].trim().length()>0){                    sb.append(result[i][j]).append("##");                }else{                    sb.append("@@").append("##");                }            }            if(sb.toString().endsWith("##")){                sb.delete(sb.toString().length()-2, sb.toString().length());            }            System.out.println(sb.toString());            list.add(sb.toString());        }        return list;    }

然後根據上面在編寫一個讀取Excel2003和一個Excel2007的類就行了。

以上是個人在測試編寫後做的一點記錄,有不對的地方望指正和見諒。

 

java讀取excel檔案資料匯入mysql資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.