jxl导入导出Excel

导入Excel表格:

1>导入jxl的jar包



2>jsp:


<form action="uploadFile" enctype="multipart/form-data" method="post">
<input type="file" name="upfile" /> <input type="submit" value="上传" />
</form>
注意这里是"action",要和servlet中的WebServlet对应上

做文件上传时,必须设置enctype="multipart/form-data"这个属性
表示文件以流的形式进行传输。这样后台才能获取得到

3>sevlet:
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
        
        //获取文件部件part
        Part part = request.getPart("upfile");
        
        try {
        	//选取Excel文件得到工作薄Workbook
        	Workbook book= Workbook.getWorkbook(part.getInputStream());
        	//通过Workbook的getSheet方法选择第一个工作表(从0开始)
        	Sheet sheet = book.getSheet(0);
        	//打印行列
        	System.out.println(sheet.getColumns());
        	System.out.println(sheet.getRows());
        	//循环取到每个单元格
        	 for(int i=0;i<sheet.getRows();i++){
                 for(int j=0;j< sheet.getColumns ();j++){
                	 //获取每个单元格
                     Cell cell1=sheet.getCell(j,i);  
                     String result=cell1.getContents();  
                     System.out.print(result+"  ");
                 }
                 System.out.println();
             }	 
        	 book.close();
        	
		} catch (BiffException e) {
          e.printStackTrace();
		}
        
	}




导出Excel表格:


把页面中的table导出为excel表格:


<body>
<table class="table  table-condensed table-striped">
        <tr>
            <th>编号</th>
            <th>班级名称</th>
            <th>班级人数</th>
            <th>开班日期</th>
            <th>结束日期</th>
            <th>操作</th>
        </tr>
           <tr>
            <td>1001</td>
            <td>java一班</td>
              <td>30</td>
            <td>2014-12-12</td>
            <td>2015-12-12</td>
            <th>
            <a href="classinfo_update.html">修改</a> 
            <a href="">删除</a>
            </th>
        </tr>         <tr>
            <td>1001</td>
            <td>java一班</td>
              <td>30</td>
            <td>2014-12-12</td>
            <td>2015-12-12</td>
            <th>
            <a href="classinfo_update.html">修改</a> 
            <a href="">删除</a>
            </th>
        </tr>         <tr>
            <td>1001</td>
            <td>java一班</td>
              <td>30</td>
            <td>2014-12-12</td>
            <td>2015-12-12</td>
            <th>
            <a href="classinfo_update.html">修改</a> 
            <a href="">删除</a>
            </th>
        </tr>   
                  
                             
    </table>
</body>

查看: tomcat安装目录 --> conf -->  web.xml中有doc、xls等输出格式类型:

    <mime-mapping>
        <extension>xls</extension>
        <mime-type>application/vnd.ms-excel</mime-type>
    </mime-mapping>

直接用<mime-type>里面的值就可

把JSP里面的contentType设置为:


contentType="application/vnd.ms-excel; charset=UTF-8"


打开页面的时候就可以直接保存为一个EXCEL文件







你可能感兴趣的:(java,Excel,表单)