SSM框架導入導出

1.導包 或直接注入maven依賴

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

2、寫一個工具類或者直接寫在service中,本人是寫在了service中,如果有多個需要導出導入的的地方,那就最好寫成工具類。

service層

    //導出
    public void export(List<ExamcountWithBLOBs> exam,OutputStream out);

    //導入
   public List<ExamcountWithBLOBs> importExcel(MultipartFile file);

serviceImpl

//這是將標籤替換,單獨抽取了出來,方便調用
public String replaceP(String content){
        //它遇到\r\n的時候會自動換行
        //獲取要導出的內容把裏面的<P> 換成"" ,把</P>換成\r\n
        //把$nbsp;  替換成空格
        content=content.replaceAll("<p>","");
        content=content.replaceAll("&nbsp;", " ");
        content=content.replaceAll("</p>", "\r\n");
        return content;
    }
    //導出
    public void export(List<ExamcountWithBLOBs> exam,OutputStream out){
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet hs = wb.createSheet("考試信息統計表");
            HSSFRow hr = hs.createRow(0);
            HSSFCell hc = hr.createCell(0);
            //第一行表頭
            hc.setCellValue("考試統計列表");
            //合併單元格
            hs.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));
            //設置列寬
            //第一個屬性是第幾列,第二個是列的寬度 
            // 由於下面定義的列是以數組的形式存在,所以列數是從 0 開始的 
            hs.setColumnWidth(0, 20*256);
            hs.setColumnWidth(1, 20*256);
            hs.setColumnWidth(2, 50*256);
            hs.setColumnWidth(3, 50*256);
            hs.setColumnWidth(4, 50*256);
            hs.setColumnWidth(5, 50*256);
            hs.setColumnWidth(6, 50*256);
            hs.setColumnWidth(7, 50*256);
            hs.setColumnWidth(8, 50*256);

            //設置格式
            HSSFCellStyle style=wb.createCellStyle();
            //自動換行
            style.setWrapText(true);
            //水平居中
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            //垂直居中
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            //合併單元格
            HSSFRow hf2 = hs.createRow(1);
            //第二行每列的列名
            String [] title = {"班級","講師","本週課程進度","當前班級學生情況概述","本週考試內容","本週考試成績及分析說明","班級學員問題及解決情況","總結","時間"};
            for (int i = 0; i < title.length; i++) {
                hf2.createCell(i).setCellValue(title[i]);
                }
            //後面有多少行由list的size決定
            for(int i=0; i<exam.size();i++){
                //創建行
                HSSFRow rowi = hs.createRow(i+2);

                //創建列
                //第一列
                HSSFCell cell0=rowi.createCell(0);
                cell0.setCellStyle(style); 
                String  cname=exam.get(i).getC_name();
                cell0.setCellValue(cname);

                HSSFCell cell1=rowi.createCell(1);
                //調用格式
                cell1.setCellStyle(style); 
                //獲取內容
                String  uname=exam.get(i).getUser().getuName();
                //將內容添加到對應的列
                cell1.setCellValue(uname);
                /*rowi.createCell(0).setCellValue(exam.get(i).getC_name());
                rowi.createCell(1).setCellValue(exam.get(i).getUser().getuName());*/

                HSSFCell cell2=rowi.createCell(2);
                cell2.setCellStyle(style); 
                String  progress=exam.get(i).geteStudyprogress();
                progress=replaceP(progress);
                cell2.setCellValue(progress);

                HSSFCell cell3=rowi.createCell(3);
                cell3.setCellStyle(style);
                String studycase=exam.get(i).geteStudycase();
                //調用標籤替換的方法,替換掉數據庫中存在的多餘的標籤
                //如果有另外的標籤需要替換自己添加進替換方法中
                studycase=replaceP(studycase);
                cell3.setCellValue(studycase);

                HSSFCell cell4=rowi.createCell(4);
                cell4.setCellStyle(style);
                String content=exam.get(i).geteExamcontent();
                content=replaceP(content);
                cell4.setCellValue(content);

                HSSFCell cell5=rowi.createCell(5);
                cell5.setCellStyle(style);
                String gradeandanalyze=exam.get(i).geteGradeandanalyze();
                gradeandanalyze=replaceP(gradeandanalyze);
                cell5.setCellValue(gradeandanalyze);

                HSSFCell cell6=rowi.createCell(6);
                cell6.setCellStyle(style);
                String program=exam.get(i).geteProgramandanalyze();
                program=replaceP(program);
                cell6.setCellValue(program);

                HSSFCell cell7=rowi.createCell(7);
                cell7.setCellStyle(style);
                String count=exam.get(i).geteCount();
                count=replaceP(count);
                cell7.setCellValue(count);

//時間一定要用 toLocaleString()方法轉換爲String格式,不能用toString()方法              rowi.createCell(8).setCellValue(exam.get(i).geteDate().toLocaleString());

            }
            //下載
            try {
                wb.write(out);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        //導入
        /**MultipartFile file  設置成MultipartFile 類型是因爲在springmvc-action.xml中設置文件上傳大小的beand的類型爲MultipartFile,所以只要跟文件上傳有關的file都必須設置爲MultipartFile 類型
        如果設置一邊是是MultipartFile 類型,另外地方設置爲File類型,則會造成 java.lang.File.init的BUG出現,所以最好都都設定爲MultipartFile類型
        <!-- 文件上傳的 
          id不能隨便起 必須是multipartResolver
          -->
          <bean  id="multipartResolver" 
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <!-- 文件上傳的大小 -->
          <property name="maxUploadSize" value="99999999"></property> 
          </bean>   
**/

        public List<ExamcountWithBLOBs> importExcel(MultipartFile file){

            List<ExamcountWithBLOBs> list = new ArrayList<ExamcountWithBLOBs>();
            try {
                InputStream in =file.getInputStream();
                Workbook wb = new HSSFWorkbook(in);
                Sheet sheet = wb.getSheetAt(0);
                //定義一個list來獲取內容
                //獲取列  行 內容
                for (Row row : sheet) {
                    //第一行  第二行不獲取
                    if(row.getRowNum()<2){
                        continue;
                    }
                    //定義一個user對象
                    ExamcountWithBLOBs exam=new ExamcountWithBLOBs();
                    exam.setC_name(row.getCell(1).getStringCellValue());
                    exam.seteStudyprogress(row.getCell(2).getStringCellValue());
                    exam.seteStudycase(row.getCell(3).getStringCellValue());
                    exam.seteExamcontent(row.getCell(4).getStringCellValue());
                    exam.seteGradeandanalyze(row.getCell(5).getStringCellValue());
                    exam.seteProgramandanalyze(row.getCell(6).getStringCellValue());
                    exam.seteCount(row.getCell(7).getStringCellValue());
                    /*exam.seteDate(new Date(row.getCell(8).getStringCellValue()));*/

                    //放到list裏
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        exam.seteDate(sdf.parse(row.getCell(8).getStringCellValue()));
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    list.add(exam);
                }
                return list;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

controller

//導出
    //導出excel  導出的controller方法返回值類型爲void
        @RequestMapping("/exam/exportExcel.action")
        public void exportExcel(HttpServletResponse response,String start,String end){
            //這是根據時間查詢,可以隨意換成其他查詢方式
            Map<String, String> map=new HashMap<String, String>();
            map.put("time1",start );
            map.put("time2",end);
            List<ExamcountWithBLOBs> list=examService.findTimeToTime(map);

            OutputStream out=null;
            try {
                out=response.getOutputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //告訴瀏覽器以下載 的方式打開
            response.setHeader("Content-disposition", "attachment;filename=exam.xls");
            //設置響應類型
            response.setContentType("application/msexcel");
            examService.export(list, out);

        }

        //導入excel MultipartFile Importfile這個Importfile一定要跟jsp頁面中的file的name相對應
        @RequestMapping("/exam/imporExcel.action")
        public String importExcel(MultipartFile Importfile){
            //導入File 獲取file 從頁面獲取
            System.out.println(Importfile+"sssssssssssssss");
            List<ExamcountWithBLOBs> list=examService.importExcel(Importfile);
            //利用循環添加
            for (ExamcountWithBLOBs exam : list) {

                examService.add(exam);
            }
            return "/kstj/kstj";
        }

jsp頁面

//導出
        function doExportExcel(){

            window.open("${pageContext.request.contextPath }/exam/exportExcel.action?start="+t2+"&end="+t1);
     }
<input type='button' value='導出' class='s_button' onclick='doExportExcel()''/>&nbsp;
//導入   form的類型enctype="multipart/form-data"一定要設置
<form  action="${pageContext.request.contextPath }/exam/imporExcel.action" method="post" enctype="multipart/form-data">
                    <input name="Importfile" type="file">
                    <input type="submit" value="導入" />
                </form>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章