分享

web中使用POI导入导出EXCEL文件的例子

 hehffyy 2011-07-18

struts1.x的例子,struts2.x可以参考自己修改
1.action的写法

Java代码  收藏代码
  1. import java.io.*;  
  2. import java.sql.*;  
  3. import java.util.ArrayList;  
  4.   
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8. import org.apache.poi.hssf.usermodel.*;  
  9. import org.apache.struts.action.*;  
  10. import org.apache.struts.upload.FormFile;  
  11. import org.apache.commons.beanutils.BeanUtils;  
  12.   
  13. public class Action {  
  14.  /**//* 
  15.   * 把数据库中的字段导入到Excel ,并生成Excel文档 
  16.   **/  
  17.  public ActionForward getDownload(ActionMapping actionMapping,  
  18.    ActionForm actionForm, HttpServletRequest request,  
  19.    HttpServletResponse response) throws Exception {  
  20.   Form fm = (Form) actionForm;  
  21.   // Excel 文件存放在服务器的相对路径下  
  22.   String outputFile = request.getRealPath("/tmp/Excel.xls");  
  23.     
  24.   try {  
  25.    // 创建新的Excel 工作簿  
  26.    HSSFWorkbook workbook = new HSSFWorkbook();  
  27.    // 在Excel 工作簿中建一工作表  
  28.    HSSFSheet sheet = workbook.createSheet("Sheet1");  
  29.    // 设置单元格格式(文本)  
  30.    HSSFCellStyle cellStyle = workbook.createCellStyle();  
  31.    cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));  
  32.      
  33.    // 在索引0的位置创建行(第一行)  
  34.    HSSFRow row = sheet.createRow((short0);  
  35.      
  36.    HSSFCell cell1 = row.createCell((short0);// 第一列  
  37.    HSSFCell cell2 = row.createCell((short1);  
  38.    HSSFCell cell3 = row.createCell((short2);  
  39.    // 定义单元格为字符串类型  
  40.    cell1.setCellType(HSSFCell.CELL_TYPE_STRING);  
  41.    cell2.setCellType(HSSFCell.CELL_TYPE_STRING);  
  42.    cell3.setCellType(HSSFCell.CELL_TYPE_STRING);  
  43.      
  44.    cell1.setEncoding(HSSFCell.ENCODING_UTF_16);  
  45.    cell2.setEncoding(HSSFCell.ENCODING_UTF_16);  
  46.    cell3.setEncoding(HSSFCell.ENCODING_UTF_16);  
  47.    // 在单元格中输入数据  
  48.    cell1.setCellValue("姓名");  
  49.    cell2.setCellValue("性别");  
  50.    cell3.setCellValue("年龄");  
  51.      
  52.    Connection connection = session.connection();  
  53.      
  54.    String sql = "Select t.name, t.sex, t.age from table t where t.sex = ?";  
  55.      
  56.    try {  
  57.     PreparedStatement ps = connection.prepareStatement(sql);  
  58.     ps.setString(1, fm.getSex());// 传入查询条件  
  59.     ResultSet rs = ps.executeQuery();// 查询结果存入rs  
  60.     connection.commit();// 执行SQL  
  61.       
  62.     while (rs.next()) {  
  63.     //设置j行从第二行开始  
  64.      int j = 1;  
  65.      row = sheet.createRow((short) j);  
  66.      //设置i列从第二列开始  
  67.      for (int i = 1; i <= 3; i++) {  
  68.       HSSFCell cell = row.createCell((short) (i-1));  
  69.       // 设置单元格格式  
  70.       cell.setCellStyle(cellStyle);  
  71.       cell.setCellType(HSSFCell.CELL_TYPE_STRING);  
  72.       cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  73.       cell.setCellValue(rs.getString(i));  
  74.      }  
  75.        
  76.      j++;  
  77.     }  
  78.       
  79.     request.setAttribute("message""文件生成成功!");  
  80.    } catch (SQLException e) {  
  81.     request.setAttribute("message""创建文件失败!");  
  82.     e.printStackTrace();  
  83.    }  
  84.    // 删除路径下同名的Excel 文件  
  85.    File path = new File(outputFile);  
  86.    path.delete();  
  87.      
  88.    // 新建一输出文件流  
  89.    FileOutputStream fOut = new FileOutputStream(outputFile);  
  90.    // 把相应的Excel 工作簿存盘  
  91.    workbook.write(fOut);  
  92.    // 操作结束,关闭文件  
  93.    fOut.flush();  
  94.    fOut.close();  
  95.     //该处如果Excel过大会影响效率,谁有好的想法可以提出来参考(不过从页面下载完后就会清空)  
  96.    request.getSession().setAttribute("Download", outputFile);  
  97.      
  98.   } catch (Exception ioexception) {  
  99.    request.setAttribute("message""创建文件失败!");  
  100.    return actionMapping.findForward("outJSP");  
  101.   }  
  102.     
  103.   return actionMapping.findForward("outJSP");  
  104.  }  
  105.    
  106.  /**//* 
  107.   * 从Excel文件中读取数据,并导入到数据库中 
  108.   **/  
  109.   public ActionForward getUpload(ActionMapping actionMapping,  
  110.    ActionForm actionForm, HttpServletRequest request,  
  111.    HttpServletResponse response) throws Exception {  
  112.   // 获取excel 文件  
  113.   Form fm = (Form) actionForm;  
  114.   FormFile formfile = fm.getUploadfile();  
  115.   InputStream inputstream = formfile.getInputStream();  
  116.   fm.clear();// 清空  
  117.   Session session = HibernateSession.currentSession();  
  118.   ArrayList list = new ArrayList();  
  119.   int input = 0//导入记数  
  120.   String name = null;  
  121.   String sex = null;  
  122.   String age = null;  
  123.     
  124.   try {  
  125.    //通过得到的文件输入流inputstream创建一个HSSFWordbook对象  
  126.          HSSFWorkbook hssfworkbook = new HSSFWorkbook(inputstream);  
  127.          HSSFSheet hssfsheet = hssfworkbook.getSheetAt(0);//第一个工作表  
  128.    HSSFRow hssfrow = hssfsheet.getRow(0);//第一行  
  129.      
  130.    //遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数  
  131.             for (int i = 0; i < hssfworkbook.getNumberOfSheets(); i++) {  
  132.              hssfsheet = hssfworkbook.getSheetAt(i);  
  133.                
  134.              //遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数  
  135.                 for (int j = 1; j < hssfsheet.getPhysicalNumberOfRows(); j++) {  
  136.                  hssfrow = hssfsheet.getRow(j);  
  137.                  //判断是否还存在需要导入的数据  
  138.                     if (hssfrow == null) {  
  139.                      System.out.println("这里已没有数据,在第"+i+"列,第"+j+"行");  
  140.                      break;  
  141.                     }  
  142.                     /** *//**将EXCEL中的第 j 行,第一列的值插入到实例中*/  
  143.                     if (hssfrow.getCell((short0) == null) {  
  144.                      name = "";  
  145.                     } else if (hssfrow.getCell((short0).getCellType() == 0) {  
  146.                      name = new Double(hssfrow.getCell((short0).getNumericCellValue()).toString();  
  147.                     }  
  148.                     //如果EXCEL表格中的数据类型为字符串型  
  149.                     else {  
  150.                      name = hssfrow.getCell((short0).getStringCellValue().trim();  
  151.                     }  
  152.                     /** *//**将EXCEL中的第 j 行,第二列的值插入到实例中*/  
  153.                     //姓名  
  154.                     if(hssfrow.getCell((short1) == null){  
  155.                      sex = "";  
  156.                     } else if(hssfrow.getCell((short1).getCellType() == 0) {  
  157.                         sex = new Double(hssfrow.getCell((short1).getNumericCellValue()).toString();  
  158.                     }  
  159.                     //如果EXCEL表格中的数据类型为字符串型  
  160.                     else {  
  161.                         sex = hssfrow.getCell((short1).getStringCellValue().trim();  
  162.                     }  
  163.                     /** *//**将EXCEL中的第 j 行,第三列的值插入到实例中*/  
  164.                     //姓名  
  165.                     if(hssfrow.getCell((short1) == null){  
  166.                      age = "";  
  167.                     } else if(hssfrow.getCell((short1).getCellType() == 0) {  
  168.                         age = new Double(hssfrow.getCell((short1).getNumericCellValue()).toString();  
  169.                     }  
  170.                     //如果EXCEL表格中的数据类型为字符串型  
  171.                     else {  
  172.                         age = hssfrow.getCell((short1).getStringCellValue().trim();  
  173.                     }  
  174.                       
  175.                     name = name.trim();  
  176.                     sex = sex.toUpperCase();  
  177.                       
  178.                     if (name.equals("")) {  
  179.                      error.setName(name);  
  180.                      error.setMessage("姓名不能为空");  
  181.                        
  182.                      list.add(error);  
  183.                      continue;  
  184.                     } else {  
  185.                      fm.setName(name);  
  186.                      fm.setSex(sex);  
  187.                      fm.setAge(age);  
  188.                        
  189.                      session.save(fm);  
  190.                     }  
  191.                     //导入成功加1  
  192.                     input++;  
  193.                 }  
  194.             }  
  195.               
  196.             session.saveObjs(list.toArray());  
  197.         } catch () {  
  198.            
  199.         }  
  200.  }  
  201. }  

 

2.Form的写法

Java代码  收藏代码
  1. import org.apache.struts.action.ActionForm;  
  2. import org.apache.struts.upload.FormFile;  
  3.   
  4. public class Form extends ActionForm {  
  5.  // 上传的文件  
  6.  private FormFile _flddo;  
  7.    
  8.  public void setUploadfile(FormFile formfile) {  
  9.   _flddo = formfile;  
  10.  }  
  11.    
  12.  public FormFile getUploadfile() {  
  13.   return _flddo;  
  14.  }  
  15.    
  16.  public void clear() {  
  17.   _flddo = null;  
  18.  }  
  19. }  

 

3.上传页面Upload.jsp

Java代码  收藏代码
  1. <%@ page contentType="text/html; charset=GBK" language="java"%>  
  2. <%@ taglib uri="http://jakarta./struts/tags-html" prefix="html"%>  
  3.   
  4. <html>  
  5.  <html:form action="/Action.do?method=getUpload" method="POST" enctype="multipart/form-data">  
  6.   <html:file property="uploadfile" size="80%" />  
  7.   <input type="button" value="导 入" onclick="upload(this.form)" class="buttonGray">  
  8.  </html:form>  
  9. </html>  
  10.   
  11. <script language="javascript">  
  12. function upload(obj)  
  13. {  
  14.  if(confirm("您现在选择的是XXX,您确定要导入吗?"))  
  15.  {  
  16.   var uploadfile = document.all.uploadfile.value;  
  17.   if((null == uploadfile) ||( "" == uploadfile))  
  18.   {  
  19.    alert("上传文件没有指定!");  
  20.    return false;  
  21.   }  
  22.      obj.action = '<html:rewrite page="/Action.do?method=getUpload"/>';  
  23.      obj.submit();  
  24.  }  
  25. }  
  26. </script>  

 

4.下载页面Download.jsp

Java代码  收藏代码
  1. <%@ page contentType="text/html; charset=GBK"%>  
  2. <%@ taglib uri="http://jakarta./struts/tags-html" prefix="html" %>  
  3. <%@ taglib uri="http://jakarta./struts/tags-bean" prefix="bean" %>  
  4.   
  5. <%  
  6. //获取下载文件  
  7.  String download = (String) request.getSession().getAttribute("Download");  
  8. //清空文件  
  9.  request.getSession().removeAttribute("Download");  
  10. %>  
  11.   
  12. <html>  
  13.  下传文件 <a href="<%=download %>" name="下载">下载</a>  
  14. </html>  

 


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

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多