当前位置 : 主页 > 编程语言 > java >

Java里的下载Excel模板上传Excel文件(网络收集)

来源:互联网 收集:自由互联 发布时间:2021-06-28
Controller------导出excel模板 public void leadToExcel(HttpServletRequest request, HttpServletResponse response) { excelUtil = new ExcelUtil(); try { // excel表格的表头,map LinkedHashMap fieldMap = new LinkedHashMap (); fieldMap.p
Controller------导出excel模板
public void leadToExcel(HttpServletRequest request,  
            HttpServletResponse response) {  
  
        excelUtil = new ExcelUtil();  
        try {  
            // excel表格的表头,map  
            LinkedHashMap
 
   fieldMap = new LinkedHashMap
  
   (); fieldMap.put("studentCode", "学号"); fieldMap.put("studentName", "学生姓名"); fieldMap.put("teachClass", "班级名称"); fieldMap.put("dailyResult", "平时成绩"); String sheetName = "平时成绩"; // 导出模板 excelUtil.leadToExcel(fieldMap, sheetName, response); } catch (Exception e) { e.printStackTrace(); } }
  
 
工具类excelUtil.leadToExcel
/** 
     * 导出Excel模板 
     * 
     * @param fieldMap 
     *            类的英文属性和Excel中的中文列名的对应关系 
     * @param sheetName 
     *            工作表的名称 
     * @param response 
     *            使用response可以导出到浏览器 
     * @throws ExcelException 
     *             异常 
     */  
    public 
 
   void leadToExcel(LinkedHashMap
  
    fieldMap, String sheetName, HttpServletResponse response) throws ExcelException { // 设置默认文件名为当前时间:年月日时分秒 String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format( new Date()).toString(); // 如果文件名没提供,则使用时间戳 if (fileName == null || fileName.trim().equals("")) { // 设置默认文件名为当前时间:年月日时分秒 fileName = new SimpleDateFormat("yyyyMMddhhmmss") .format(new Date()).toString(); } // 设置response头信息 response.reset(); response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件 response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls"); // 创建工作簿并发送到浏览器 try { OutputStream out = response.getOutputStream(); int sheetSize = 65535; // 创建工作簿并发送到OutputStream指定的地方 WritableWorkbook wwb; try { wwb = Workbook.createWorkbook(out); // 因为2003的Excel一个工作表最多可以有65536条记录,除去列头剩下65535条 // 所以如果记录太多,需要放到多个工作表中,其实就是个分页的过程 // 1.计算一共有多少个工作表 // double sheetNum = Math.ceil(list.size() // / new Integer(sheetSize).doubleValue()); double sheetNum = 1; // 2.创建相应的工作表,并向其中填充数据 // 如果只有一个工作表的情况 if (1 == sheetNum) { WritableSheet sheet = wwb.createSheet(sheetName, 1); // 定义存放英文字段名和中文字段名的数组 String[] enFields = new String[fieldMap.size()]; String[] cnFields = new String[fieldMap.size()]; // 填充数组 int count = 0; for (Entry
   
     entry : fieldMap.entrySet()) { enFields[count] = entry.getKey(); cnFields[count] = entry.getValue(); count++; } // 填充表头 for (int i = 0; i < cnFields.length; i++) { Label label = new Label(i, 0, cnFields[i]); sheet.addCell(label); } // 设置自动列宽 setColumnAutoSize(sheet, 5); } wwb.write(); wwb.close(); } catch (Exception e) { e.printStackTrace(); // 如果是ExcelException,则直接抛出 if (e instanceof ExcelException) { throw (ExcelException) e; // 否则将其它异常包装成ExcelException再抛出 } else { throw new ExcelException("导出Excel失败"); } } } catch (Exception e) { e.printStackTrace(); // 如果是ExcelException,则直接抛出 if (e instanceof ExcelException) { throw (ExcelException) e; // 否则将其它异常包装成ExcelException再抛出 } else { throw new ExcelException("导出Excel失败"); } } }
   
  
 
Controller导入excel文件
/** 
 * 导入 
 *  
 * @author 刘新阳 
 * @version 1.0.0 , 2016年3月30日15:51:51 
 * @return 
 */  
  
@RequestMapping(value = "importDailyResult", method = RequestMethod.POST)  
public void importDailyResult(HttpServletResponse response,  
        HttpServletRequest request) throws Exception {  
    // 创建一个通用的多部分解析器  
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(  
            request.getSession().getServletContext());  
    InputStream inExcelFile = null;  
    String dataBaseName = "itoo_basic";  
    // 判断 request 是否有文件上传,即多部分请求  
    if (multipartResolver.isMultipart(request)) {  
        // 转换成多部分request  
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;  
  
        // 取得request中的所有文件名  
        Iterator
 
   iter = multiRequest.getFileNames();  
        while (iter.hasNext()) {  
            // 记录上传过程起始时的时间,用来计算上传时间  
            int pre = (int) System.currentTimeMillis();  
            // 取得上传文件  
            MultipartFile file = multiRequest.getFile(iter.next());  
            try {  
                inExcelFile = file.getInputStream();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
  
        }  
  
    }  
  
    // 创建一个list 用来存储读取的内容  
    List list = new ArrayList();  
    Workbook rwb = null;  
    Cell cell = null;  
  
    String result = "error";  
  
    // 获取Excel文件对象  
    try {  
        rwb = Workbook.getWorkbook(inExcelFile);  
    } catch (BiffException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    } catch (IOException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }  
  
    // 获取文件的指定工作表 默认的第一个  
    Sheet sheet = rwb.getSheet(0);  
  
    // 行数(表头的目录不需要,从1开始)  
    for (int i = 0; i < sheet.getRows(); i++) {  
  
        // 创建一个数组 用来存储每一列的值  
        String[] str = new String[sheet.getColumns()];  
  
        // 列数  
        for (int j = 0; j < sheet.getColumns(); j++) {  
  
            // 获取第i行,第j列的值  
            cell = sheet.getCell(j, i);  
            str[j] = cell.getContents();  
  
        }  
        // 把刚获取的列存入list  
        list.add(str);  
    }  
    List studentList = new ArrayList();  
    List teachClassList = new ArrayList();  
    List studentResult = new ArrayList();  
    String teachCode= (String) request.getSession().getAttribute("name");  
            //"1240364";  
    String teacherId =questionBean.QueryTeachid(dataBaseName, teachCode) ;  
  
    List
  
   studentResultlist=new ArrayList
   
    (); String termId=request.getParameter("termId"); if (list.size() > 0) { for (int i = 1; i < list.size(); i++) { StudentResult studentResultEntity= new StudentResult(); Object[] o = (Object[]) list.get(i); String studentCode = o[0].toString(); String teachClassName = o[2].toString(); String dailyResult = o[3].toString(); // 1.判断学生表中是否存在该学号。根据学生学号查询学生id studentList = studentResultBean.querystudentId(dataBaseName, studentCode); if (studentList.size() > 0) { String StudentId = studentList.get(0).toString(); // 2.判断上课班中是否存在该上课班名称,并根据上课班名称查询上课班id teachClassList = studentResultBean.queryteachClassId( dataBaseName, teachClassName); // 3.根据学生id和上课班id判断学生成绩表中是否已经存在该学生在该上课班的成绩,如果存在删提示,如果不存在则插入 if (teachClassList.size() > 0) { String teachClassId = teachClassList.get(0).toString(); //4.根据学年id,上课班id,教师id查询成绩规则id String resultRuleId=studentResultBean.queryResultId(dataBaseName, termId, teachClassId, teacherId); studentResult = studentResultBean .queryStudentByStudentIdandTeachClassId( dataBaseName, teachClassId, StudentId); if (studentResult.size()== 0) { // 5.将学生和上课班以及平时成绩加入到学生成绩实体。 studentResultEntity.setStudentId(StudentId); studentResultEntity.setTeachClassId(teachClassId); studentResultEntity.setDaliyResult(dailyResult); studentResultEntity.setRemark("未判分"); studentResultEntity.setOperator("lxy"); studentResultEntity.setDataBaseName(dataBaseName); studentResultEntity.setResultRuleId(resultRuleId); studentResultlist.add(studentResultEntity); } } } } boolean flag= studentResultBean.saveStudenResult(studentResultlist); if (flag) { result = "success"; } } JacksonJsonUntil jacksonJsonUntil = new JacksonJsonUntil(); jacksonJsonUntil.beanToJson(response, result); }
   
  
 
网友评论