java中用jxl方式實現EXCEL導入/導出(詳情版)

pom導入包

    <dependency>
        <groupId>net.sourceforge.jexcelapi</groupId>
        <artifactId>jxl</artifactId>
        <version>2.6.12</version>
    </dependency>

pojo類

package com.example.demo.pojo;

import java.io.Serializable;

public class User implements Serializable {
   
    private Long id;
    private String name;
    private Integer sex;
    private String memo;
    private Integer age;

    private static final long serialVersionUID = 1L;
   
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
  
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }
    
    public Integer getSex() {
        return sex;
    }
   
    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getMemo() {
        return memo;
    }

    public void setMemo(String memo) {
        this.memo = memo == null ? null : memo.trim();
    }

    public Integer getAge() {
        return age;
    }
   
    public void setAge(Integer age) {
        this.age = age;
    }

   
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", name=").append(name);
        sb.append(", sex=").append(sex);
        sb.append(", memo=").append(memo);
        sb.append(", age=").append(age);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

1–處理導入的excel數據

package com.example.demo.common;

import jxl.Sheet;
import jxl.Workbook;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: fileImportandexport
 * @description: 導入文件成excel
 * @author: KJH
 * @create: 2019-04-28 09:09
 */
public class ImportExcelCommon {

    /**
      *@Description: 導入excel
      *@Param: File file
      *@return: List<Object> list list第一個數據是行(共幾行) 第二個是列(共幾列)
      *@Author: KJH
      *@date:
      **/
    public  List<Object> importExcel(File file){
        List<Object> list=new ArrayList();
        try {
           //1獲取文件
            Workbook book=Workbook.getWorkbook(file);
            //2獲得第一個工作表對象
            Sheet sheet=book.getSheet(0);
            //3得到所有的列,行
            int rows=sheet.getRows();//行
            int colums=sheet.getColumns();//列
            list.add(rows);
            list.add(colums);
            //4遍歷數據
            for (int i = 1; i < rows; i++) {
                for (int j = 0; j < colums; j++) {
                    if(Tools.notEmpty(sheet.getCell(j,i).getContents())) {
                        list.add(sheet.getCell(j,i).getContents().trim());//得到數據並添加到list中
                    }
                }
            }
            //5.關閉資源
            book.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    return  list;
    }
}

2.處理導入文件,獲取結果添加到數據庫

package com.example.demo.controller;


import com.example.demo.common.DateUtil;
import com.example.demo.common.ImportExcelCommon;
import com.example.demo.common.InterfaceBase;
import com.example.demo.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: fileImportandexport
 * @description: 需要導入的數據
 * @author: KJH
 * @create: 2019-04-28 09:13
 */
@Controller
@RequestMapping
public class ImportManageController extends InterfaceBase {
    @RequestMapping(value = "/index")
    public String index(){
        return "/import/import";
    }

    @RequestMapping(value = "/import")
    public void exportManagee(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return;
            }
            String fileName = file.getOriginalFilename();//獲取文件名稱
            String prefix = fileName.substring(fileName.lastIndexOf("."));// 獲取文件後綴
            File excelFile = File.createTempFile(DateUtil.getSdfTimes(), prefix);//生成文件
            file.transferTo(excelFile);//生成臨時文件,結束後要刪除
            List<User> userList = new ArrayList<User>();//新增到數據庫的list
            ImportExcelCommon importExcelCommon = new ImportExcelCommon();
            List<Object> list = importExcelCommon.importExcel(excelFile);//用於存放獲取導入的信息
            if (!list.isEmpty() && list.size() > 2) {
                //2. 對得到的內容進行處理,放到對象中
                int rows = (int) list.get(0) - 1;//得到行,並減去第一行數據(有標題-1,沒有就不用-1)
                int count = 2;//list 前兩個數據固定成行和列了,所以下表從2開始
                int colums = (int) list.get(1);//得到列
                for (int i = 0; i < rows; i++) {
                    User user = new User();
                    user.setName(list.get(count).toString());
                    user.setSex(Integer.parseInt( list.get(count + 1).toString()));
                    user.setAge( Integer.parseInt(list.get(count + 2).toString()));
                    user.setMemo(list.get(count + 3).toString());
                    userList.add(user);
                    count += colums;//下次添加數據從這列添加數據之後去添加 如第一列4 從list下標2,第二次從list下標 6
                }
            }
        if (userList.size()>0){
            for (User user : userList) {
                userService.insert(user);
            }
        }
         //刪除臨時文件
        this.deleteFile(excelFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * @Title: deleteFile
     * @Description: 刪除臨時添加的數據
     * @param   files
     * @return void
     * @author KJH
     * @date  2018年9月12日 上午11:09:12
     * @version V1.0
     * @throws
     */
    private void deleteFile(File... files) throws Exception {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }
}

3–導出數據處理公共類

package com.example.demo.common;

import jxl.SheetSettings;
import jxl.Workbook;
import jxl.format.*;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @program: fileImportandexport
 * @description: 導出文件成excel
 * @author: KJH
 * @create: 2019-04-28 09:09
 */
public class ExportExcelCommon {

    /**
     *@Description: 導出公共類
     *@Param: HttpServletResponse response, Map< Integer, Object> map, Map< Integer, Object> maps
     *@return:
     *@Author: KJH
     *@date:
     **/
    public  void exportExcel(HttpServletResponse response, Map< Integer, Object> map, Map< Integer, Object> maps) {
        //1.生成文件名稱
        String fileName= DateUtil.getSdfTimes()+".xls";
        //2.設置編碼,格式,頭
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/x-excel");
        response.addHeader("Content-Disposition", "attachment;filename=" +fileName);
        //3.創建excel,設置格式
        try {
            //創建一個excel的sheet
            WritableWorkbook workbook= Workbook.createWorkbook(response.getOutputStream());
            //定義單元格格式 可以設置字體,顏色等
            WritableCellFormat wf=new WritableCellFormat();
            wf.setAlignment(Alignment.CENTRE);//中心對齊
//            //設置背景顏色;
//            wf.setBackground(Colour.BLUE_GREY);
//            //設置邊框;
//            wf.setBorder(Border.ALL, BorderLineStyle.DASH_DOT);
//            //設置自動換行;
//            wf.setWrap(true);
//            //設置文字居中對齊方式;
//            wf.setAlignment(Alignment.CENTRE);
//            //設置垂直居中;
//            wf.setVerticalAlignment(VerticalAlignment.CENTRE);
            WritableSheet sheet=null;
            SheetSettings settings=null;
            for (int i = 0; i <1; i++) {
                sheet = workbook.createSheet("用戶信息列表",i);
                settings=sheet.getSettings();
                settings.setVerticalFreeze(1);
                //添加第一行標題
                int o=0;
                for (Map.Entry<Integer, Object> entrys : map.entrySet()) {
                    sheet.addCell(new Label(o,0,entrys.getValue()+"", wf));
                    o+=1;
                }
                //處理數據
                if(maps.size()>0) {
                    int h=0;//行
                    int l=0;//列
                    int s=0;//代表當一行所有列都添加進去後s++,然後重新複製行和列
                    for (Map.Entry<Integer, Object> entry : maps.entrySet()) {
                        if(0==s) {
                            l=0;//列
                            h+=1;//行
                        } else if (0 == s % map.size()){
                            l=0;//列
                            h++;//行
                        }
                        //第1行 0 0 - - 1 0 -- 2 0 - -
                        //第2行 0 1 - - 1 1 -- 3 1 - -
                        sheet.addCell(new Label(l++,h,entry.getValue()+"",wf));
                        s+=1;
                    }
                }
            }
            workbook.write();//寫入excel
            workbook.close();//關閉資源
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

4–查詢獲取結果,然後調用公共類處理數據

package com.example.demo.controller;

import com.example.demo.common.ExportExcelCommon;
import com.example.demo.common.InterfaceBase;
import com.example.demo.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @program: fileImportandexport
 * @description: 需要導出的數據
 * @author: KJH
 * @create: 2019-04-28 09:13
 */
@RestController
@RequestMapping
public class ExportManageController extends InterfaceBase {

    @RequestMapping(value = "/export")
    public  void  exportManagee(HttpServletResponse response,User user){
        Map< Integer, Object> map=new TreeMap<Integer, Object>();//添加導出數據第一行的內容
        Map< Integer, Object> maps=new TreeMap<Integer, Object>();//添加導出數據(從第二行開始)
//        map.put(0,"ID");
        map.put(0,"名稱");
        map.put(1,"性別");
        map.put(2,"年齡");
        map.put(3,"記錄");
        List<User> userList = userService.selectAll();
        try {
        //3遍歷數據內容
           if (!userList.isEmpty() && userList.size()>0){
               for (int i = 0; i< userList.size(); ) {
//                       maps.put(i,userList.get(i).getId());
                       maps.put(i+0,userList.get(i).getName());
                       maps.put(i+1,userList.get(i).getSex());
                       maps.put(i+2,userList.get(i).getAge());
                       maps.put(i+3,userList.get(i).getMemo());
                       i+=map.size();
               }
           }
            ExportExcelCommon exportExcelCommon=new ExportExcelCommon();
            exportExcelCommon.exportExcel(response,map,maps);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

源碼地址

[email protected]:kongjihui/study.git

版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章