小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

web中使用POI導(dǎo)入導(dǎo)出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.   * 把數(shù)據(jù)庫中的字段導(dǎo)入到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 文件存放在服務(wù)器的相對(duì)路徑下  
  22.   String outputFile = request.getRealPath("/tmp/Excel.xls");  
  23.     
  24.   try {  
  25.    // 創(chuàng)建新的Excel 工作簿  
  26.    HSSFWorkbook workbook = new HSSFWorkbook();  
  27.    // 在Excel 工作簿中建一工作表  
  28.    HSSFSheet sheet = workbook.createSheet("Sheet1");  
  29.    // 設(shè)置單元格格式(文本)  
  30.    HSSFCellStyle cellStyle = workbook.createCellStyle();  
  31.    cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));  
  32.      
  33.    // 在索引0的位置創(chuàng)建行(第一行)  
  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.    // 在單元格中輸入數(shù)據(jù)  
  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();// 查詢結(jié)果存入rs  
  60.     connection.commit();// 執(zhí)行SQL  
  61.       
  62.     while (rs.next()) {  
  63.     //設(shè)置j行從第二行開始  
  64.      int j = 1;  
  65.      row = sheet.createRow((short) j);  
  66.      //設(shè)置i列從第二列開始  
  67.      for (int i = 1; i <= 3; i++) {  
  68.       HSSFCell cell = row.createCell((short) (i-1));  
  69.       // 設(shè)置單元格格式  
  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""創(chuàng)建文件失?。?);  
  82.     e.printStackTrace();  
  83.    }  
  84.    // 刪除路徑下同名的Excel 文件  
  85.    File path = new File(outputFile);  
  86.    path.delete();  
  87.      
  88.    // 新建一輸出文件流  
  89.    FileOutputStream fOut = new FileOutputStream(outputFile);  
  90.    // 把相應(yīng)的Excel 工作簿存盤  
  91.    workbook.write(fOut);  
  92.    // 操作結(jié)束,關(guān)閉文件  
  93.    fOut.flush();  
  94.    fOut.close();  
  95.     //該處如果Excel過大會(huì)影響效率,誰有好的想法可以提出來參考(不過從頁面下載完后就會(huì)清空)  
  96.    request.getSession().setAttribute("Download", outputFile);  
  97.      
  98.   } catch (Exception ioexception) {  
  99.    request.setAttribute("message""創(chuàng)建文件失敗!");  
  100.    return actionMapping.findForward("outJSP");  
  101.   }  
  102.     
  103.   return actionMapping.findForward("outJSP");  
  104.  }  
  105.    
  106.  /**//* 
  107.   * 從Excel文件中讀取數(shù)據(jù),并導(dǎo)入到數(shù)據(jù)庫中 
  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//導(dǎo)入記數(shù)  
  120.   String name = null;  
  121.   String sex = null;  
  122.   String age = null;  
  123.     
  124.   try {  
  125.    //通過得到的文件輸入流inputstream創(chuàng)建一個(gè)HSSFWordbook對(duì)象  
  126.          HSSFWorkbook hssfworkbook = new HSSFWorkbook(inputstream);  
  127.          HSSFSheet hssfsheet = hssfworkbook.getSheetAt(0);//第一個(gè)工作表  
  128.    HSSFRow hssfrow = hssfsheet.getRow(0);//第一行  
  129.      
  130.    //遍歷該表格中所有的工作表,i表示工作表的數(shù)量 getNumberOfSheets表示工作表的總數(shù)  
  131.             for (int i = 0; i < hssfworkbook.getNumberOfSheets(); i++) {  
  132.              hssfsheet = hssfworkbook.getSheetAt(i);  
  133.                
  134.              //遍歷該行所有的行,j表示行數(shù) getPhysicalNumberOfRows行的總數(shù)  
  135.                 for (int j = 1; j < hssfsheet.getPhysicalNumberOfRows(); j++) {  
  136.                  hssfrow = hssfsheet.getRow(j);  
  137.                  //判斷是否還存在需要導(dǎo)入的數(shù)據(jù)  
  138.                     if (hssfrow == null) {  
  139.                      System.out.println("這里已沒有數(shù)據(jù),在第"+i+"列,第"+j+"行");  
  140.                      break;  
  141.                     }  
  142.                     /** *//**將EXCEL中的第 j 行,第一列的值插入到實(shí)例中*/  
  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表格中的數(shù)據(jù)類型為字符串型  
  149.                     else {  
  150.                      name = hssfrow.getCell((short0).getStringCellValue().trim();  
  151.                     }  
  152.                     /** *//**將EXCEL中的第 j 行,第二列的值插入到實(shí)例中*/  
  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表格中的數(shù)據(jù)類型為字符串型  
  160.                     else {  
  161.                         sex = hssfrow.getCell((short1).getStringCellValue().trim();  
  162.                     }  
  163.                     /** *//**將EXCEL中的第 j 行,第三列的值插入到實(shí)例中*/  
  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表格中的數(shù)據(jù)類型為字符串型  
  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.                     //導(dǎo)入成功加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="導(dǎo) 入" onclick="upload(this.form)" class="buttonGray">  
  8.  </html:form>  
  9. </html>  
  10.   
  11. <script language="javascript">  
  12. function upload(obj)  
  13. {  
  14.  if(confirm("您現(xiàn)在選擇的是XXX,您確定要導(dǎo)入嗎?"))  
  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>  

 


    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多