1. 程式人生 > >導入導出功能

導入導出功能

vid ftl cati subst int transacti ndt bug servlet

一,步驟

1.導入:

一.ftl

<form id="form" action="" enctype="multipart/form-data" method="post"  >
    <input type="file" id="fileID" name="fileName" class="btn dropdown-toggle btn-primary" style="width: 220px; float:left;" />                    
     <input type="hidden" name="projectId" id="projectId" value="">
    <input type="button" value="導入源聲" onclick="importList();" class
="btn dropdown-toggle btn-success" style="margin-left:20px;"/> </form> 註意:後臺獲取屬性的值,必須指定 name = "" 二.js function importList() { var filePath = $("#fileID").val(); if (filePath == ‘‘) { alert(‘請選擇文件!‘); return; } if(pnationId == ‘-1‘ || nationId == ‘-1‘){ alert(
‘請選擇國家!‘); return; } var form = $("#form"); var projectId = GetQueryString("projectId "); $(‘#projectId‘).val(projectId); form.attr("action", "/nps/analysis/import"); form.attr("method", "POST"); form.submit(); } //獲取projectId function GetQueryString(name) { var reg
= new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } 三.controller @RequestMapping(value="/analysis/import",method = RequestMethod.POST) public String importSource(HttpServletRequest request,@RequestParam("fileName") CommonsMultipartFile file, Integer projectId){ InputStream in =null; String msg = ""; try { in = file.getInputStream(); msg = npsSourceAnalysisService.importList(in, file.getOriginalFilename(),pnationId,nationId); in.close(); } catch (IOException e) { e.printStackTrace(); logger.info(e.getMessage()); msg = "導入失敗!"; } finally { if (in != null) { try { in.close(); // 關閉流 } catch (IOException e) { logger.debug("in close IOException:" + e.getMessage()); } } } return "redirect:/nps/analysis/list?projectId="+projectId+"&msg="+msg; } 四.service public String importList(InputStream in,String fileName); @Transactional public String importList(InputStream in, String fileName,Integer pnationId,Integer nationId) { String[][] table = null; String msg = null; try { table = ExcelUtils.readExcel(in,fileName,0); } catch (Exception e) { e.printStackTrace(); return "文件導入失敗,請檢查文件格式!"; } Map<String,Integer> tableColumMap = new HashMap<String, Integer>(); if (CheckUtils.isNullOrBlank(table) || table.length == 0) { return "表格中沒有任何數據!"; } if (table.length == 1) { return "表格中只存在表頭數據!"; } //校驗導入文件內容 for (int i = 0; i < table[0].length; i++) { String cell = table[0][i].trim(); tableColumMap.put(cell, i); } List<String> errorMsgs = new ArrayList<String>(); String[] titles ={"ID","描述","產品名稱","型號","版本","時間","次數","得分(問題1)","得分(問題2)"}; for (int i = 0; i < titles.length; i++) { String title = titles[i]; if(!tableColumMap.containsKey(title)){ errorMsgs.add("Excel表格表頭列有誤,不存在"+title+"列,請修改Excel後導入"); if(errorMsgs.size() >= 10) return "導入文件表頭不正確,請檢查後重新導入!"; } } if (errorMsgs.size() == 0) { NPSSourceAnalysis npsSourceAnalysis=new NPSSourceAnalysis(); for (int i = 1; i < table.length; i++) { String sourceID = table[i][tableColumMap.get("ID")].trim(); String descript = table[i][tableColumMap.get("描述")].trim(); String product = table[i][tableColumMap.get("名稱")].trim(); String inner = table[i][tableColumMap.get("型號")].trim(); String ROM = table[i][tableColumMap.get("版本")].trim(); String createTime = table[i][tableColumMap.get("時間")].trim(); String SN = table[i][tableColumMap.get("SN")].trim(); String CSR = table[i][tableColumMap.get("得分(問題1)")].trim(); String recommend = table[i][tableColumMap.get("得分(問題2)")].trim(); npsSourceAnalysis.setSourceID(Integer.parseInt(sourceID)); npsSourceAnalysis.setDescript(descript); npsSourceAnalysis.setProduct(product); npsSourceAnalysis.setInnerVersion(inner); npsSourceAnalysis.setOuterVersion(outer); npsSourceAnalysis.setROM(ROM); npsSourceAnalysis.setCreateTime(createTime); npsSourceAnalysis.setSN(SN); npsSourceAnalysis.setCSR(Integer.parseInt(CSR)); npsSourceAnalysis.setRecommend(Integer.parseInt(recommend)); npsSourceAnalysis.setHandled(0); npsSourceAnalysis.setAbroad(0); npsSourceAnalysis.setPnationId(pnationId); npsSourceAnalysis.setNationId(nationId); nPSSourceAnalysisMapper.insert(npsSourceAnalysis); } } else{ for (String errorMsg : errorMsgs) { msg = msg + errorMsg +";"; } } return msg; } 五,需要的工具類 ExcelUtils.readExcel() 六.依賴 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.16-beta1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16-beta1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency <!-- https://mvnrepository.com/artifact/org.samba.jcifs/jcifs --> <dependency> <groupId>org.samba.jcifs</groupId> <artifactId>jcifs</artifactId> <version>1.2.19</version> </dependency>

2.導出:

一.Controller
/**
* 源聲分析結果導出
*/
@RequestMapping(value = "/devide/explorExcel", method = { RequestMethod.POST })
public void  explorExcel(HttpServletRequest request,HttpServletResponse response) throws CSException {
    Integer projectId = Integer.valueOf(request.getParameter("projectId"));
    String starttime = request.getParameter("starttime");
    String endtime = request.getParameter("endtime");    
    List<Version> versions=versionService.getVersionListByProjectId(projectId);        
    String  product=versions.get(0).getProduct();        
    List<NPSAnalysisDevide> list = npsAnalysisDevideService.selectAllBad(product,starttime,endtime);            
    npsAnalysisDevideService.exportList(response,list,product);    
                                    
}

二.service
public void exportList(HttpServletResponse response, List<NPSAnalysisDevide> list,String projectName);

@Override
public void exportList(HttpServletResponse response,List<NPSAnalysisDevide> items,String projectName) {
        
    BuildExcelUtils bEUtils = new BuildExcelUtils(items,projectName){
        @Override
        public void buildDataTo2007Excel(ExcelWrite2007 excel,XSSFSheet sheet, XSSFCellStyle contentFormat,List<?> items,String projectName) {
            @SuppressWarnings("unchecked")
            List<NPSAnalysisDevide> list = (List<NPSAnalysisDevide>) items;
            int rowIdx = 0;
            for (NPSAnalysisDevide item : list) {
                rowIdx++;                    
                excel.setVal(sheet, rowIdx, 0, item.getSourceID(), contentFormat);
                excel.setVal(sheet, rowIdx, 1, item.getDescript(), contentFormat);
                excel.setVal(sheet, rowIdx, 2, item.getProduct(), contentFormat);
                excel.setVal(sheet, rowIdx, 3, item.getInnerVersion(), contentFormat);
                excel.setVal(sheet, rowIdx, 4, item.getOuterVersion(), contentFormat);
                excel.setVal(sheet, rowIdx, 5, item.getROM(), contentFormat);
                excel.setVal(sheet, rowIdx, 6, item.getCreateTime(), contentFormat);
                excel.setVal(sheet, rowIdx, 6, item.getCreateTime(), contentFormat);
                excel.setVal(sheet, rowIdx, 7, item.getSN(), contentFormat);
                excel.setVal(sheet, rowIdx, 8, item.getCSR(), contentFormat);
                excel.setVal(sheet, rowIdx, 9, item.getRecommend(), contentFormat);                    
                excel.setVal(sheet, rowIdx, 10, item.getClassfy(), contentFormat);
                excel.setVal(sheet, rowIdx, 11, item.getOpinion(), contentFormat);
                excel.setVal(sheet, rowIdx, 12, item.getEmotion(), contentFormat);
                excel.setVal(sheet, rowIdx, 13, item.getRegional(), contentFormat);
                excel.setVal(sheet, rowIdx, 14, item.getNationStr(), contentFormat);
            }                
        }
    };
    int[] redTitleCols = {};//設置紅色樣式的列表頭
    int[] colsWidths = {3000,3000,5000,15000,2500,2500,3500,5000,5000,2000,3000,3000,3000,3000,3000};//設置列寬        
    bEUtils.exportExcel("結果", historyTitle,redTitleCols ,colsWidths, response);        
}
三.工具類
BuildExcelUtils

四.依賴

<dependency>
       <groupId>org.apache.poi</groupId>
       <artifactId>poi-ooxml</artifactId>
       <version>3.16-beta1</version>
</dependency>
        
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16-beta1</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.1</version>
</dependency

導入導出功能