Java通過apache poi 讀取excel(.xlsx)文件,並通過MyBbtis插入數據庫中

1.與數據庫對應的實體類

package com.scysun.entity;


public class Classify {
int id;  //主鍵
String name;  
int parentsNameId;  //所屬類的ID,因爲上傳的表中有分類結構 ,表截圖在後面有

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getParentsNameId() {
return parentsNameId;
}
public void setParentsNameId(int parentsNameId) {
this.parentsNameId = parentsNameId;
}
@Override
public String toString() {
return "Classify [id=" + id + ", name=" + name + ", parentsNameId=" + parentsNameId + "]";
}


}


2.創建對應的數據表結構 

create table classify(
id int not null auto_increment,primary key(id),
        name varchar(40),
parentsNameId int
);


3.讀取文件

package com.scysun.readExcel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.scysun.entity.Classify;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class PoiWithExcel {
	public List<Classify> read(){
		
		List<Classify> list = new ArrayList<Classify>();
		try {  
            FileInputStream file = new FileInputStream("D:\\zhiming\\51分類.xlsx");  
            //獲取工作薄 
            XSSFWorkbook workbook = new XSSFWorkbook(file);  
            //獲取工作表  
            XSSFSheet sheet = workbook.getSheetAt(0);  
            //遍歷每一行 
            //Iterator<Row> rowIterator = sheet.iterator();  
            //獲取總行數
            int rowCount = sheet.getPhysicalNumberOfRows();
            //記錄空行數
            int emptyNumber = 0;
            
            //行循環
            for(int r=1;r<=rowCount;r++) {  
            	 Row row = sheet.getRow(r);
            	  //如果爲空行
                 if(sheet.getRow(r)==null){
                	 continue;   
                 }
                 int cellCount = row.getLastCellNum();
                 //int g = 0;
                 /*for(int m=0;m<cellCount;m++){
                	 
            		 if(row.getCell(m).getStringCellValue()==""){
            			 g = g+1;
            			 if(g==cellCount){
            				//System.out.println(g);
            				continue;        
            			 }
            			 
            		 }
            		 
            	 }*/
                
                if(isRowEmpty(row)==false){
                	emptyNumber++;
                	continue;
                }
                //列循環
                for(int c=0;c<cellCount;c++) {
                	String cellValue = row.getCell(c).getStringCellValue();
                	
                	Cell cell = row.getCell(c);
                    if(cellValue==""){
                    	continue;
                    }
                    Classify cf = new Classify();
                    cf.setId(r-emptyNumber);
                    cf.setName(row.getCell(c).getStringCellValue());
                    
                   
                    if(c>=1){
                    	for(int r1=r;r1>=1;r1--){
                    		if(sheet.getRow(r1).getCell(c-1).getStringCellValue()!=""){
                    			cf.setParentsNameId(sheet.getRow(r1).getCell(c-1).getRowIndex()-emptyNumber);
                    			break;
                    		}	
                    	}
                    }else{
                    	cf.setParentsNameId(r-emptyNumber);
                    }
                    list.add(cf);
                    //System.out.print(cell);
                }   
                
                //System.out.println(""); 
            }
            
            file.close();
            //System.out.println(rowCount);
         
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }
		return list;
	  
	}
	
	//判斷是否是空行
	public static boolean isRowEmpty(Row row) {
		int g = 0;
	    for (int c=0; c < row.getPhysicalNumberOfCells(); c++) {
	        Cell cell = row.getCell(c);
	        String cellValue = cell.getStringCellValue().trim();
	        if(cellValue==""){
	        	g = g+1;
	        	if(g==row.getPhysicalNumberOfCells()){
	        		return false;     
    			 }
	        	
	        }  
	    }
		return true;
	}
	
	/*public static void main(String[] args) {
		PoiWithExcel pwe = new PoiWithExcel();
		List list = pwe.read();
		for(int i=0;i<list.size();i++){
			System.out.println(list.get(i));
		}
	}*/

}

4.MyBatis的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	 <typeAliases>
     	<package name="com.scysun.entity"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/> 
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3305/lable?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <mapper resource="com/scysun/config/Classify.xml"/>
    </mappers>
   
</configuration>

5.MyBatis映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.scysun.config">
    	<select id="selectClassify" resultType="Classify">
    		select * from classify;
    	</select>
    	
    	<insert id="insertClassify" parameterType="Classify">
    		insert into classify(name,parentsNameId) values(#{name},#{parentsNameId});
    	</insert>
    	
    	<insert id="insert" parameterType="Classify">
    		insert into classify(name,parentsName) values(#{name},#{parentsName});
    	</insert>
    	
		<delete id="deleteClassify" parameterType="Classify">
			delete from classify where id>=77;
		</delete>
		
		<update id="updateClassify" parameterType="Classify">
			update classify set name=#{name} where id=#{id};
		</update>
		
    </mapper>


6.執行SQL操作

package com.scysun.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.scysun.entity.Classify;
import com.scysun.readExcel.PoiWithExcel;

public class Test {
	
	
	public static void main(String[] args) {
		String resource = "mybatis-config.xml";
		try {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	        SqlSession session=sqlSessionFactory.openSession(); 
	        //insertAllTo(session);
	        //insertIntoClassify(session);
	        selectAll(session);
	        //session.delete("deleteClassify");
	        session.commit();
	        session.close();
	        //System.out.println("刪除成功");
	        //System.out.println("插入成功");
		} catch (IOException e) {
			e.printStackTrace();
		}
        
	}
	
	public static void insertAllTo(SqlSession session){
		PoiWithExcel pwe = new PoiWithExcel();
		List<Classify> list = pwe.read();
		for(Classify classify : list){
        	session.insert("insertClassify", classify);
        }
	}
	
	public static void selectAll(SqlSession session){
		List<Classify> list = session.selectList("selectClassify");
		for(Classify classify : list){
			System.out.println(classify);
		}
	}
	
	public static void insertIntoClassify(SqlSession session){
		Classify c = new Classify();
		c.setName("新增一條數據");
		//c.setParentsName("新增數據的所屬類");
		session.insert("insert", c);
	}
}

7.這是我要上傳的文件截圖





8.項目用的包


自己也是剛入坑沒多久,有什麼問題,歡迎隨時留言相互交流學習

































發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章