分享

静态页面导出excel

 昵称9880406 2012-05-04
需要jxl.jar包
java:
ToExcel.java----servlet
public class ToExcel extends HttpServlet {
  public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("utf-8"); //防止乱码
  String fileName ="test"; //设置导出的文件名称
  String contextType="application/vnd.ms-excel"; //定义导出文件格式的字符串
  String recommendName =new String(fileName.getBytes(),"utf-8"); //设置文件名称的编码格式
  response.setHeader("Content-Disposition","attachment;filename="+recommendName+".xls");
  response.setCharacterEncoding(contextType);  //设置导出文件格式
  String[] str1 =request.getParameterValues("name");
  String[] str2 = request.getParameterValues("age");
  String[] name =new String[100];
  name[0]="姓名";
  System.arraycopy(str1, 0, name, 1, str1.length); //将str1数组拷贝到name中
  String[] age =new String[100];
  age[0]="年龄";
  System.arraycopy(str2,0, age, 1, str2.length);
  List list = new ArrayList();
  list.add(name);
  list.add(age);  
  OutputStream os = response.getOutputStream();
  WritableWorkbook wwb = null;
  WritableSheet sheet = null;
  Label label = null;
  try{
wwb = Workbook.createWorkbook(os);
  }catch(IOException e){
   e.printStackTrace();
  }
   if(wwb != null){
    sheet = wwb.createSheet("sheet1",0);
   }
   for(int i =0;i<list.size();i++){
    System.out.println(list.get(i));
    String[] str =(String [])list.get(i);
    for(int j=0;j<str.length;j++){
     label=new Label(i,j,str[j]);  //竖着排列
//     label=new Label(j,i,str[j]); //横着排列
     try {
      sheet.addCell(label);
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   }
   response.resetBuffer();
   wwb.write();
   try {
    wwb.close();
   } catch (WriteException e) {
    e.printStackTrace();
   }
  os.flush();
 os.close();
 }
}
 
jsp:
<body>
   <form action="/MyDesign/ToExcel" method="post" >
   <table>
   <tr>
   <td>姓名:</td>
   <td><input type="text" name="name"></td>
   <td>年龄:</td>
   <td><input type="text" name="age"></td>
   </tr>
    <tr>
   <td>姓名:</td>
   <td><input type="text" name="name"></td>
   <td>年龄:</td>
   <td><input type="text" name="age"></td>
   </tr>
    <tr>
   <td>姓名:</td>
   <td><input type="text" name="name"></td>
   <td>年龄:</td>
   <td><input type="text" name="age"></td>
   </tr>
    <tr>
   <td>姓名:</td>
   <td><input type="text" name="name"></td>
   <td>年龄:</td>
   <td><input type="text" name="age"></td>
   </tr>
    <tr>
   <td>姓名:</td>
   <td><input type="text" name="name"></td>
   <td>年龄:</td>
   <td><input type="text" name="age"></td>
   </tr>
   </table>
   <input type="submit" value="提交" >
   </form>
  </body>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约