SSM框架poi實現(xiàn)Excel導入

第一次擼項目偿渡,使用SSM框架臼寄,需要用Excel導入學生信息,花了很長的時間卸察,特此記錄下來脯厨,分享給大家铅祸,有什么問題希望不要見怪坑质,本人是剛入門的小白。

首先看一項目結構

image

一临梗、pojo下定義兩個實體類涡扼,一個是對于excel文件,解析它的數據(ExcelBean)盟庞,另一個是導入數據庫表的實體類(student)
ExcelBean.java

import org.apache.poi.xssf.usermodel.XSSFCellStyle;
 
public class ExcelBean implements java.io.Serializable {  
    private String headTextName;//列頭(標題)名  
    private String propertyName;//對應字段名  
    private Integer cols;//合并單元格數  
    private XSSFCellStyle cellStyle;  
      
    public ExcelBean(){  
          
    }  
    public ExcelBean(String headTextName, String propertyName){  
        this.headTextName = headTextName;  
        this.propertyName = propertyName;  
    }  
      
    public ExcelBean(String headTextName, String propertyName, Integer cols) {  
        super();  
        this.headTextName = headTextName;  
        this.propertyName = propertyName;  
        this.cols = cols;  
    }   
      
    public String getHeadTextName() {  
       return headTextName;  
   }  
 
   public void setHeadTextName(String headTextName) {  
       this.headTextName = headTextName;  
   }  
 
   public String getPropertyName() {  
       return propertyName;  
   }  
 
   public void setPropertyName(String propertyName) {  
       this.propertyName = propertyName;  
   }  
 
   public Integer getCols() {  
       return cols;  
   }  
 
   public void setCols(Integer cols) {  
       this.cols = cols;  
   }  
 
   public XSSFCellStyle getCellStyle() {  
       return cellStyle;  
   }  
 
   public void setCellStyle(XSSFCellStyle cellStyle) {  
       this.cellStyle = cellStyle;  
   }  
}  

student.java

public class Student {
    //用戶id
    private Long id;
    //用戶登錄名
    private String username;
    //用戶密碼
    private String password;
    private String classname;
    private  String num;

    public Long getId(String stringCellValue) {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    public String getNum() {
        return num;
    }

    public void setNum(String num) {
        this.num = num;
    }

    public void setUserName(String valueOf) {
        this.username = username == null ? null : username.trim();
    }

    public String getClassname() {
        return classname;
    }

    public void setClassname(String classname) {
        this.classname = classname;
    }
}

二吃沪、定義mapper文件(SSM里面就是這種結構,相當于DAO文件一樣)什猖。
StudentMapper.java

public interface StudentMapper {
    Student login(String username);
    int deleteByPrimaryKey(Long id);
     int insert(Student record);
    int insertSelective(Student record);
    Student selectByPrimaryKey(Long id);
    int updateByPrimaryKeySelective(Student record);
    int updateByPrimaryKey(Student record);
    void insertInfoBatch(List<Student> list);
}

StudentMapper.xml

 <mapper namespace="cn.ds.mapper.StudentMapper">


    <resultMap type="cn.ds.pojo.Student" id="BaseResultMap">
        <id column="id" property="id" />
        <result column="username" property="username" />
        <result column="password" property="password" />
        <result column="classname" property="classname"  />
        <result column="num" property="num"  />
    </resultMap>
    <sql id="Base_Column_List" >
      id, username, password,classname,num
  </sql>
    <!-- 用戶登錄的方法 id與方法名中相同  持久層-->
    <select id="login" parameterType="cn.ds.pojo.Student" resultType="Student">
        select * from student where username = #{username}
    </select>
    <insert id="insertInfoBatch" parameterType="java.util.List">
        insert into student (id, username, password,classname,num)
        values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{id,jdbcType=INT},
            #{userName,jdbcType=VARCHAR},
            #{password,jdbcType=VARCHAR} ,
            #{classname,jdbcType=VARCHAR},
            #{num,jdbcType=VARCHAR})
        </foreach>
    </insert>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Long"  >
        select *from student
        where id = #{id}
    </select>
    <insert id="insert" parameterType="cn.ds.pojo.Student" >
    insert into Student (id, username, password,classname,num)
    values (#{id}, #{username}, #{password},
            #{classname}, #{num})
  </insert>
    <update id="updateByPrimaryKey" parameterType="cn.ds.pojo.Student" >
    update student
    set username = #{username},
      password = #{password},
            classname = #{classname},
      num = #{num}
    where id = #{id}
  </update>
</mapper>

三票彪、util下ExcelUtils工具類(也就是解析EXCEL文件红淡,判斷EXCEL的類型以及數據的類型)


public class ExcelUtils {

private final static Stringexcel2003L =".xls";    //2003- 版本的excel

    private final static Stringexcel2007U =".xlsx";  //2007+ 版本的excel

    /**

    * 描述:獲取IO流中的數據,組裝成List<List<Object>>對象

    * @param in,fileName

    * @return

    * @throws IOException

*/

    public  List>getBankListByExcel(InputStream in,String fileName)throws Exception{

List> list =null;

        //創(chuàng)建Excel工作薄

        Workbook work =this.getWorkbook(in,fileName);

        if(null == work){

throw new Exception("創(chuàng)建Excel工作薄為空降铸!");

        }

Sheet sheet =null;  //頁數

        Row row =null;  //行數

        Cell cell =null;  //列數

        list =new ArrayList>();

        //遍歷Excel中所有的sheet

        for (int i =0; i < work.getNumberOfSheets(); i++) {

sheet = work.getSheetAt(i);

            if(sheet==null){continue;}

//遍歷當前sheet中的所有行

            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {

row = sheet.getRow(j);

                if(row==null||row.getFirstCellNum()==j){continue;}

//遍歷所有的列

                List li =new ArrayList();

                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {

cell = row.getCell(y);

                    li.add(this.getValue(cell));

                }

list.add(li);

            }

}

return list;

    }

/**

* 描述:根據文件后綴在旱,自適應上傳文件的版本

    * @param inStr,fileName

    * @return

    * @throws Exception

*/

    public  WorkbookgetWorkbook(InputStream inStr,String fileName)throws Exception{

Workbook wb =null;

        String fileType = fileName.substring(fileName.lastIndexOf("."));

        if(excel2003L.equals(fileType)){

wb =new HSSFWorkbook(inStr);  //2003-

        }else if(excel2007U.equals(fileType)){

wb =new XSSFWorkbook(inStr);  //2007+

        }else{

throw new Exception("解析的文件格式有誤!");

        }

return wb;

    }

/**

* 描述:對表格中數值進行格式化

    * @param cell

    * @return

    */

    //解決excel類型問題推掸,獲得數值

    public  StringgetValue(Cell cell) {

String value ="";

        if(null==cell){

return value;

        }

switch (cell.getCellType()) {

//數值型

            case Cell.CELL_TYPE_NUMERIC:

if (HSSFDateUtil.isCellDateFormatted(cell)) {

//如果是date類型則 桶蝎,獲取該cell的date值

                    Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());

                    SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd");

                    value = format.format(date);;

                }else {// 純數字

                    BigDecimal big=new BigDecimal(cell.getNumericCellValue());

                    value = big.toString();

                    //解決1234.0  去掉后面的.0

                    if(null!=value&&!"".equals(value.trim())){

String[] item = value.split("[.]");

                        if(1

value=item[0];

                        }

}

}

break;

            //字符串類型

            case Cell.CELL_TYPE_STRING:

value = cell.getStringCellValue().toString();

break;

            // 公式類型

            case Cell.CELL_TYPE_FORMULA:

//讀公式計算值

                value = String.valueOf(cell.getNumericCellValue());

                if (value.equals("NaN")) {// 如果獲取的數據值為非法值,則轉換為獲取字符串

                    value = cell.getStringCellValue().toString();

                }

break;

            // 布爾類型

            case Cell.CELL_TYPE_BOOLEAN:

value =" "+ cell.getBooleanCellValue();

break;

            default:

value = cell.getStringCellValue().toString();

        }

if("null".endsWith(value.trim())){

value="";

        }

return value;

    }

}

四、實現(xiàn)service接口
StudentServiceImpl.java

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentmapper;
    public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartFile file = multipartRequest.getFile("file");

        System.out.println("得到數據文件");
        if(file.isEmpty()){
            try {
                throw new Exception("文件不存在谅畅!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        InputStream in =null;
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("加載流");
        List<List<Object>> listob = null;
        try {
            System.out.println("加載流");
            listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //該處可調用service相應方法進行數據保存到數據庫中登渣,現(xiàn)只對數據輸出
        for (int i = 0; i < listob.size(); i++) {
            List<Object> lo = listob.get(i);
            System.out.println("遍歷" + listob.get(i));
            Student vo = new Student();
            Student j = null;

            try {
                //j = studentmapper.selectByPrimaryKey(Long.valueOf());
                j = studentmapper.selectByPrimaryKey(Long.valueOf(String.valueOf(lo.get(0))));
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                System.out.println("沒有新增");
            }

            vo.setId(Long.valueOf(String.valueOf(lo.get(0))));
            vo.setUsername(String.valueOf(lo.get(1)));
            vo.setPassword(String.valueOf(lo.get(2)));
            vo.setClassname(String.valueOf(lo.get(3)));
            vo.setNum(String.valueOf(lo.get(4)));
            if(j == null)
            {
                studentmapper.insert(vo);
            }
            else
            {
                studentmapper.updateByPrimaryKey(vo);
            }
        }
        return "success";
    }
}

五、控制層Controller
StudentController.java

@ResponseBody
    @RequestMapping(value="ajaxUpload",method={RequestMethod.GET,RequestMethod.POST})
    public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
        System.out.println("這是請求");
         return studentService.ajaxUploadExcel(request, response);
    }

六毡泻、jsp頁面

<form action="<%=basePath%>/student/ajaxUpload.do" method="post" enctype="multipart/form-data">
    請選擇Excel:<input type="file" name="file">
    <input type="submit" name="提交">
</form>

七胜茧、實現(xiàn)圖片


image.png

image.png

image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市仇味,隨后出現(xiàn)的幾起案子竹揍,更是在濱河造成了極大的恐慌,老刑警劉巖邪铲,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件芬位,死亡現(xiàn)場離奇詭異,居然都是意外死亡带到,警方通過查閱死者的電腦和手機昧碉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來揽惹,“玉大人被饿,你說我怎么就攤上這事√虏” “怎么了狭握?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵,是天一觀的道長疯溺。 經常有香客問我论颅,道長,這世上最難降的妖魔是什么囱嫩? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任恃疯,我火速辦了婚禮,結果婚禮上墨闲,老公的妹妹穿的比我還像新娘今妄。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布盾鳞。 她就那樣靜靜地躺著犬性,像睡著了一般。 火紅的嫁衣襯著肌膚如雪腾仅。 梳的紋絲不亂的頭發(fā)上仔夺,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天,我揣著相機與錄音攒砖,去河邊找鬼缸兔。 笑死,一個胖子當著我的面吹牛吹艇,可吹牛的內容都是我干的惰蜜。 我是一名探鬼主播,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼受神,長吁一口氣:“原來是場噩夢啊……” “哼抛猖!你這毒婦竟也來了?” 一聲冷哼從身側響起鼻听,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤财著,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后撑碴,有當地人在樹林里發(fā)現(xiàn)了一具尸體撑教,經...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年醉拓,在試婚紗的時候發(fā)現(xiàn)自己被綠了伟姐。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡亿卤,死狀恐怖愤兵,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情排吴,我是刑警寧澤秆乳,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站钻哩,受9級特大地震影響屹堰,放射性物質發(fā)生泄漏。R本人自食惡果不足惜憋槐,卻給世界環(huán)境...
    茶點故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一双藕、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧阳仔,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至评矩,卻和暖如春叶堆,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背斥杜。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工虱颗, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蔗喂。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓忘渔,卻偏偏與公主長得像,于是被迫代替她去往敵國和親缰儿。 傳聞我的和親對象是個殘疾皇子畦粮,可洞房花燭夜當晚...
    茶點故事閱讀 45,691評論 2 361

推薦閱讀更多精彩內容

  • 打開微博熱搜,頭條便是醫(yī)院凌晨公布監(jiān)控截圖:產婦兩次下跪與家屬溝通乖阵⌒猓看完文章才知道,這是2017年8月31日瞪浸,榆林...
    marinayu閱讀 1,351評論 1 0
  • 從阿倫圖靈首創(chuàng)人工智能儒将,以機器炸彈bomem?解決機器,到深海打敗國際象棋冠軍对蒲,到alfago在圍棋上打敗圍棋大師...
    蘇_Suu閱讀 359評論 0 0
  • 貪心問題——求最值問題 貪心問題一般都是求解最多或最少的最值問題椅棺,每一步總是得到當前最優(yōu)解(局部最優(yōu)解),若是想得...
    XDgbh閱讀 316評論 0 0
  • 前天做了一個噩夢 這幾天心情都特別低沉 感覺在一個特別脆弱的時期 我仿佛又開始習慣依賴 我有點討厭這樣的不堅強 但...
    魚木易閱讀 100評論 0 0