导入解析excel小结

导入解析excel小结

 

  控制器例子:

  

 

一.   解析excel内容插入到数据库

Vm:

<form id=’form_file’ method=’post’ enctype=’multipart/form-data’>

  <input id="uploadFile" type="file" name='uploadFile' />

  <a href=’javascirpt(void0)’ onclick=’resolv();’>解析</a>

</form>

注意:解析按钮必须是<a>标签,如果换成button,用公司的表单提交则会出错:提示不是MultipartFile请求.

Js:$(‘#form_file’).bupform(

           url:’xx.do’,

           dataType:’json’,

           onSubmit:function(){return true;},//return false则会阻止表单提交

           success:function(data){

                    //成功后的回调函数

}

);

Controller:

           处理请求的方法参数用(MultipartFile uploadFile)类型接收

           解析excel内容步骤:

  1. 通过传过来的uploadFile拿到流:

a)         ImputStream is = uploadFile.getInputStraam();

  1. 创建poiSysteam:

    fs = new POIFSFileSystem(is);

  1. 创建workbook

a)         wb = new HSSFWorkbook(fs);

   1. sheet = wb.getSheetAt(0);//拿到excel的第一个sheet

   2. 得到总行数:int rowNum = sheet.getLastRowNum();

   3. 得到excel的某一行

a)         HSSFRow row = sheet.getRow(0);//得到第0行  也就是excel的标题     

  1. 得到一行里的某个单元格:

a)         HSSFCell cell = row.getCell(0);

b)         通过HSSFCell  单元格类型拿到单元格的数据

  1. 获取单元格的type: type = cell.getCellType();
  2. HSSFCell.CELL_TYPE_FORMUL数字类型:cell.getNumericCellValue();
  3. HSSFCell.CELL_TYPE_STRING:类型cell.getRichStringCellValue();
  4. HSSFCell.CELL_TYPE_FORMULA:类型

If(HSSFDateUtil.isCellDateFormatted(cell)){

         Date date = cell.getDateCellValue();

}

  1. 身份证号避免科学计数法:

    DecimalFormat df = new DecimalFormat("0");

    cellvalue = df.format(cell.getNumericCellValue());

  1.     如果cell==null 的话,就给一个’’空字符串给他

7. 每一行的数据,可以自己定义一个类来保存,类中的字段于行里面的每一列对应

         也可以用一个Map<Integer,String>-à <行号,行里面的内容>

 

二.   下载项目中的资源

  1. 方式一:

<a href='/res/excel/广东省补贴金额表.xls'>下载excel文档模板:</a>

  1. 方式二:

Vm:<a href=’download.do?filename=广东省补贴金额表.xls’ ></a>

Controller:

         处理请求的方法:

    public void download(HttpServletResponse response,String filename){

a)       设置文件的MIME类型

    response.setContentType(getServletContext().getMimeType(filename));

b)       拿到绝对路径

    String fullFileName = “/res/excel/”+filename;

c)       response.setHeader("Content-Disposition", "attachment; filename="+ new String(filename.getBytes("GBK"), "ISO8859-1"));

d)       InputStream in = new FileInputStream(fullFileName);

e)       BufferedInputStream bis = new BufferedInputStream(in);

f)        BufferedOutputStreamout=new BufferedOutputStream(response.getOutputStream());

    int  b;

    While(b=(bis.read()!=-1){

            Out.write(b);

    }

    In.close();

    Out.flush();

    Out.close();

 

posted @ 2016-05-20 17:50  掌柜子  阅读(530)  评论(0编辑  收藏  举报