Java Excel導入導出(實戰)

1、批量導入(將excel文件轉成list)html

1. 前臺代碼邏輯前端

1)首先在html頁面加入下面的代碼(能夠忽略界面的樣式)java

<label for="uploadFile" class="label-btn">
     <img id="uploadbtn" src="../img/upload-on.png" >
     <input type="file" name="" id="uploadFileWhite" 
         onchange="personUpload('uploadFileWhite')">
</label>

2)其次在引入的js里加入如下代碼ajax

uploadData = {
    // 導入是否正在上傳文件
    personUploading:false,
    
    //後臺返回描述信息
    returnStr: "",
}

//導入文件上傳
function personUpload(id){
    if( uploadData.personUploading === true ){
        alerFunc("文件正在上傳中,請稍候");
        return false;
    }
    
    if($('#'+id)[0].files.length!=1){
        //alert("請先選擇文件");
        return false;
    }

    var file = $('#'+id)[0].files[0];
    var arr = file.name.split('.');
    if(arr[1]!='xls'){
        alerFunc("文件類型不匹配,請使用xls類型的excel導入");
         return false;
    }
    
    var sendData = new FormData();
    sendData.append('uploadFile', file);
    sendData.append('cutFileName', file.name);
    console.log("ajax請求批量上傳人員信息");
    var sendDate = new Date();
    $.ajax({
        url: "uploadImportAction!personUpload.action",
        type: 'POST',
        cache: false,
        async:true, 
        data: sendData,
        processData: false,
        contentType: false,
        dataType:"json",
        beforeSend: function(){
            uploadData.personUploading = true;
            $('#uploadWait').show();//展現等待上傳頁面
        },
        success : function(response) {
            var receiveDate = new Date();
            var costTime = receiveDate.getTime() - sendDate.getTime();
            console.log("批量上傳成功" + ",花費時間爲:" + costTime + "毫秒");
            closeUploadDiv();
            uploadData.returnStr = response.data.desc;
            if(uploadData.returnStr=='ok'){
                alerFunc("導入成功");
            }else{
                //顯示返回信息div
                show();
            }
            
        },
        complete : function(){
            uploadData.personUploading = false;
        }
    });
}

function onTrackUpload(response){
    uploadData.returnStr = response.data.desc;
    show();
}

function show(){
    $('#tipDiv').show();
    $('#tipContent').html(uploadData.returnStr);
}

2. 後臺java導入代碼邏輯spring

1)action 層數據庫

public class UploadAction extends BaseAction<Person>{
    private static final long serialVersionUID = 1L;
    private static Logger logger = Logger.getLogger(UploadAction.class);
    private UploadService uploadService;
    private File uploadFile;
    private String cutFileName;

    public String personUpload(){
        logger.info("接收批量上傳的請求");
        Date start = new Date();try {
            String desc = uploadService.personUpload(uploadFile);
            result.addData("desc", desc);
            logger.info("批量上傳成功");
        } catch (Exception e) {
            result.setResult("error");
            e.printStackTrace();
            logger.error("批量上傳失敗!" + e.getMessage());
        }
        Date end = new Date();
        long time = end.getTime() - start.getTime();
        logger.info("錄批量上傳總耗時:" + time + "毫秒");
        return SUCCESS;
    }
    
    public String getCutFileName() {
        return cutFileName;
    }

    public void setCutFileName(String cutFileName) {
        this.cutFileName = cutFileName;
    }

    public File getUploadFile() {
        return uploadFile;
    }

    public void setUploadFile(File uploadFile) {
        this.uploadFile = uploadFile;
    }

    public UploadService getUploadService() {
        return uploadService;
    }

    public void setUploadService(UploadService uploadService) {
        this.uploadService = uploadService;
    }

    public UploadAction() {
    }
    
}

2)service層json

    @Override
    public String personUpload(File uploadFile) {
        // 1,讀取Excel
        FileInputStream inFile = null;
        try {
            inFile = new FileInputStream(uploadFile);
        } catch (FileNotFoundException e) {
            logger.error("讀取excel表格失敗:" + e);
        }
        HSSFWorkbook readbook = null;
        try {
            readbook = new HSSFWorkbook(inFile);
        } catch (IOException e) {
            logger.error("建立HSSFWorkbook失敗:" + e);
        }
        // 定義執行結果
        String returnStr="";
        int successNum = 0;// 成功條數
        int failNum = 0;// 失敗條數

        int nSheetNum = readbook.getNumberOfSheets();
        if (nSheetNum > 0) {
            HSSFSheet readSheet = null;
            // 讀取第一頁
            readSheet = readbook.getSheetAt(0);
            // 從第二行開始讀取
            int first = readSheet.getFirstRowNum() + 1;
            int last = readSheet.getLastRowNum();
            HSSFRow getRow = null;
            HSSFCell getCell = null;

            for (int curIndex = first; curIndex <= last; curIndex++) {
                // 把excel單元格的內容保存到person對象
                Person person = new Person();
                getRow = readSheet.getRow(curIndex);
                // 姓名
                getCell = getRow.getCell(0);
                if (getCell != null) {
                    getCell.setCellType(Cell.CELL_TYPE_STRING);
                    person.setName(getCell.getStringCellValue());
                }
                // 性別
                getCell = getRow.getCell(1);
                if (getCell != null) {
                    // 先設置Cell的類型,而後就能夠把純數字做爲String類型讀進來了,不然報錯:Cannot get a text
                    // value from a numeric cell
                    getCell.setCellType(Cell.CELL_TYPE_STRING);
                    person.setGender(getCell.getStringCellValue());
                }
                // 描述
                getCell = getRow.getCell(2);
                if (getCell != null) {
                    getCell.setCellType(Cell.CELL_TYPE_STRING);
                    person.setDes(getCell.getStringCellValue());
                }
                
                String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                person.setLastEnterTime(currentTime);// 入庫時間
                logger.info("第"+curIndex+"行加載完畢");
                // 保存到person表
                if (person.getName() == null || person.getName() == "") {
                    failNum = failNum + 1;
                    returnStr = returnStr + "在" + curIndex + "行發生錯誤[姓名不能爲空]<br>";
                    continue;
                }
                if (person.getIdNumber() == null || person.getIdNumber() == ""){
                    failNum = failNum + 1;
                    returnStr = returnStr + "在" + curIndex + "行發生錯誤[證件號碼不能爲空]<br>";
                    continue;
                }
                person.setUpdateTime(currentTime);
                if (personDAO.saveOrUpdate(person)) {
                    successNum = successNum + 1;
                } else {
                    failNum = failNum + 1;
                    returnStr = returnStr + "在" + curIndex + "行發生錯誤[數據庫執行失敗]<br>";
                }
            }
        }
        if(failNum>0){
            return "導入成功["+successNum+"]條數據,導入失敗["+failNum+"]條數據<br>" + returnStr;
        }else{
            return "ok";
        }
        
    }

2、導出(將list轉成excel文件)微信

導出能夠分爲所有導出和批量導出,下面以批量導出爲例,直接上後臺代碼。app

1)action層框架

    public String exportByPage(){
        result.setResult(JsonResult.SUCCESS);
        logger.info("接收導出單頁Excel請求==start=="+model.toString());
        long start = System. currentTimeMillis();//毫秒數
        try{
            if (model.getStartDate() == null || "".equals(model.getStartDate()) || model.getEndDate() == null || "".equals(model.getEndDate())) {
                result.setResult(JsonResult.ERROR);
                result.setErrorMessage("開始時間和結束時間不能爲空");
                return SUCCESS;
            }
            if ("1".equals(model.getIsMatchCamera()) && (model.getMatchCameraList() == null || "".equals(model.getMatchCameraList()))) {
                result.setResult(JsonResult.ERROR);
                result.setErrorMessage("匹配的相機列表不能爲空");
                return SUCCESS;
            }
            String basePath = ServletActionContext.getServletContext().getRealPath("/download");
            System.out.println(basePath);
            List<String> cameraIdList = JSONArray.parseArray(model.getMatchCameraList(), String.class);
            pageInfo.setPageSize(pageSize);
            pageInfo.setPageNumber(pageNumber);
            ExportResult exportResult = warningsService.getExcelOutPut(cameraIdList, model, pageInfo, basePath);
            result.setExportNum(exportResult.getExportNum());
            result.setExportTaskID(exportResult.getExportTaskID());
            result.setFileURL(exportResult.getFileURL());
            result.setResult(exportResult.getResult());
            result.setErrorMessage(exportResult.getErrorMessage());
        }catch(Exception e){
            logger.error("導出單頁Excel失敗");
            result.setResult(JsonResult.ERROR);
            result.setErrorMessage("導出失敗");
            e.printStackTrace();
        }
        long end = System. currentTimeMillis();//毫秒數
        long time = end - start;
        logger.info("導出單頁Excel==end==所需毫秒數爲:"+time);
        return SUCCESS;
        
    }

2)service層

    @Override
    public ExportResult getExcelOutPut(List<String> cameraIdList, SearchBean search, PageInfo pageInfo, String path) {
        ExportResult rm = new ExportResult();
        rm.setResult(ResultMessage.SUCCESS);
        FileOutputStream bos = null;
        try {
            // 建立工做簿的實例
            HSSFWorkbook workbook = new HSSFWorkbook();// 每一個工做表格最多能夠存儲的條數
            int mus = 50000;
            // 查詢出要導出的數據
            List<Warnings> datalist = warningsDao.getHistoryWarnings(cameraIdList, search, pageInfo);
            // 導出多少個excel
            int avg = (int) datalist.size() / mus;
            //String uuid = UUID.randomUUID().toString();
            String uuid = String.valueOf(System.currentTimeMillis());
            HSSFSheet sheet = null;
            HSSFRow titlerow = null;
            HSSFCell cell = null;
            HSSFRow datarow = null;
            String fileToday = DateUtils.formatTimeYMD(new Date());
            //建立目錄rootPath
            String rootPath = path + "/warnings/"+fileToday+"/";
            //建立文件夾及刪除以前的文件
            createAndDelFile(rootPath, path,fileToday,uuid);
            for (int z = 0; z < avg + 1; z++) {
                logger.info("建立工做表實例");
                // 建立工做表實例
                sheet = workbook.createSheet("列表" + (z + 1));
                titlerow = null;
                cell = null;

                if (datalist.size() > 0) {
                    logger.info("建立表頭");
                    // 建立表頭
                    String[] title = { "監控點編號", "監控點名稱", "檢測日期時間", "檢測類型", "故障類型", "故障描述", "檢測碼流類型", "視頻質量級別",
                            "檢測錄像保存位置", "檢測錄像保存天數","錄像丟失時段描述", "報警處理結果", "報警處理描述" };
                    // 建立標題行
                    titlerow = sheet.createRow(0);

                    for (int i = 0; i < title.length; i++) {
                        // 建立單元格
                        cell = titlerow.createCell((short) i);
                        /// 爲每一個單元格賦值
                        cell.setCellValue(title[i]);
                    }
                    int firstNum = z * mus;
                    int index = 0;
                    //推送進度
                    sendWebsocketMsg(uuid, "filecopy", (int)70/(avg+1)*(z+1));
                    logger.info("用數據填充表格,firstNum="+firstNum+";datalist.size()="+datalist.size());
                    // 用數據填充表格
                    for (int i = 0; i < datalist.size(); i++) {
                        if (index == mus || (firstNum + i == datalist.size())) {
                            break;
                        }
                        short cos = 0;
                        // 建立數據行
                        datarow = sheet.createRow(i + 1);

                        // 獲得datalist中的第i個對象
                        Warnings warnings = (Warnings) datalist.get(firstNum + i);
                        setCellValue(warnings, cell, datarow, cos);
                        index++;
                    }
                    // 寫入一次文件
                    logger.info("開始建立告警導出文件");
                    //推送進度
                    //sendWebsocketMsg(uuid, "filetrans", (int)70/(avg+1)*(z+1));
                    String fileName = "warning"+fileToday+"("+z +").xls";
                    File f = new File(rootPath+uuid+"/", fileName);
                    if (!f.exists()) {
                        f.createNewFile();
                    }
                    logger.info("開始寫入告警文件");
                    bos = new FileOutputStream(f);
                    workbook.write(bos);
                    bos.flush();
                    bos.close();
                    logger.info("完成寫入告警文件");
                    //workbook.removeSheetAt(0);
                }
            }
            // 將生成的文件放入文件夾中
            logger.info("開始壓縮,告警記錄壓縮路徑:"+rootPath+ "zip/warnings_"+uuid+".zip");
            ZipCompressorByAnt zip = new ZipCompressorByAnt(rootPath+"zip/warnings_"+uuid+".zip");
            zip.compressExe(rootPath+uuid);
            logger.info("壓縮結束");
            rm.setFileURL("/videodetection/download"+"/warnings/"+fileToday+"/zip/warnings_"+uuid+".zip");
            rm.setExportTaskID(uuid);
            rm.setExportNum(datalist.size());
            sendWebsocketMsg(uuid, "filepack", 100);//推送進度
        } catch (Exception e) {
            logger.error("導出告警信息發生異常:"+e);
            rm.setResult(ResultMessage.ERROR);
            rm.setErrorMessage("導出失敗");
            e.printStackTrace();
        }
        return rm;
    }
    
    //用數據填充表格裏每行的cell
    private void setCellValue(Warnings warnings,HSSFCell cell,HSSFRow datarow,int cos){
        cell = datarow.createCell(cos++);
        cell.setCellValue(warnings.getCameraID());

        cell = datarow.createCell(cos++);
        cell.setCellValue(warnings.getCameraName());

        cell = datarow.createCell(cos++);
        cell.setCellValue(warnings.getDetectDateTime());

        cell = datarow.createCell(cos++);
        //檢測類型「real」:實時檢測;「rec」:錄像檢測
        if("real".equals(warnings.getDetectType())){
            cell.setCellValue("實時檢測");
        }else if("rec".equals(warnings.getDetectType())){
            cell.setCellValue("錄像檢測");
        }

        cell = datarow.createCell(cos++);
        cell.setCellValue(warnings.getFaultType());

        cell = datarow.createCell(cos++);
        cell.setCellValue(warnings.getFaultDesc());

        cell = datarow.createCell(cos++);
        //檢測碼流類型,包括「main」:主碼流;「slaver」:從碼流 
        if("main".equals(warnings.getDetectStream())){
            cell.setCellValue("主碼流");
        }else if("slaver".equals(warnings.getDetectStream())){
            cell.setCellValue("從碼流");
        }

        cell = datarow.createCell(cos++);
        //視頻質量級別:「highest」,「high」,「normal」,「low」,「lowest」
        cell.setCellValue(getDetectLevel(warnings.getDetectLevel()));

        cell = datarow.createCell(cos++);
        //檢測錄像保存位置,包括「plat」:平臺錄像;「pu」:前端錄像
        if("plat".equals(warnings.getDetectRecPositon())){
            cell.setCellValue("平臺錄像");
        }else if("pu".equals(warnings.getDetectRecPositon())){
            cell.setCellValue("前端錄像");
        }

        cell = datarow.createCell(cos++);
        cell.setCellValue(warnings.getDetectRecDuration());

        cell = datarow.createCell(cos++);
        cell.setCellValue(getRecLostPeriodDesc(warnings.getRecLostPeriod()));//錄像丟失時段描述

        cell = datarow.createCell(cos++);
        cell.setCellValue(getWarningHandle(warnings));//報警處理結果
        
        cell = datarow.createCell(cos++);
        cell.setCellValue(warnings.getWarningHandleDesc());
    }
    
    //建立文件夾及刪除以前的文件
    private void createAndDelFile(String rootPath,String path,String fileToday,String uuid){
        File file = new File(rootPath);
        if (!file.exists()) {
            file.mkdirs();
        }else{
            //刪除昨天及之前的導出文件
            deleteDir(new File(path + "/warnings/"), fileToday);
        }
        //建立壓縮文件文件夾
        File fileZip = new File(rootPath+"zip/");
        if (!fileZip.exists()) {
            fileZip.mkdirs();
        }
        //建立某一客戶端導出xls文件路徑
        File fileXLS = new File(rootPath+uuid+"/");
        if (!fileXLS.exists()) {
            fileXLS.mkdirs();
        }
    }

以上就是批量導入導出的代碼。看起來是否是也很簡單呢,後臺框架使用的是struts2,spring,hibernate

歡迎關注微信公衆號【Java典籍】,收看更多Java技術乾貨!

  ▼微信掃一掃下圖↓↓↓二維碼關注

 

相關文章
相關標籤/搜索