`
long_yu2
  • 浏览: 311731 次
社区版块
存档分类
最新评论

Poi 读写Excel 合并ExcelSheet Struts2实现

    博客分类:
  • java
阅读更多

网上有许多人在找这样的例子,有多个Excel,要把他们合并到一个Excel里面,这里涉及无非是Excel的读取和Sheet的合并。

我做了这样一个实现,可以参考,当然更希望指点。使用Struts实现他的上传功能,在把多个Excel上传到Action后,进行合并,然后直接执行下载。也就是说,我们一个Action里要动用Struts2的上传和下载两个功能。

实现的步骤:

1.拷贝Struts的包到工程(估计都会吧,Ctrl+C 加 Ctrl + V)

2.在Web.xml里配置Struts2,也不难

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  5.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  6.     <filter>  
  7.         <filter-name>struts2</filter-name>  
  8.         <filter-class>  
  9.             org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  
  10.         </filter-class>  
  11.     </filter>  
  12.     <filter-mapping>  
  13.         <filter-name>struts2</filter-name>  
  14.         <url-pattern>/*</url-pattern>  
  15.     </filter-mapping>  
  16.     <welcome-file-list>  
  17.         <welcome-file>index.jsp</welcome-file>  
  18.     </welcome-file-list>  
  19. </web-app>  

 

3.定义Struts2的配置文件

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5. <struts>  
  6.     <!-- 一些基本配置,自己看着办 -->  
  7.     <constant name="struts.devMode" value="false"></constant>  
  8.     <constant name="struts.i18n.reload" value="true"></constant>  
  9.     <constant name="struts.i18n.encoding" value="UTF-8"></constant>  
  10.     <constant name="struts.multipart.saveDir" value="C:\\"></constant>  
  11.     <constant name="struts.multipart.maxSize" value="20971520"></constant>  
  12.     <package name="default" namespace="/" extends="struts-default">  
  13.         <action name="doUpload"  
  14.             class="com.golden.action.StrutsFileUpload">  
  15.             <result name="success" type="stream">  
  16.                 <param name="contentType">  
  17.                     application/vnd.ms-excel  
  18.                 </param>  
  19.                 <param name="contentDisposition">  
  20.                     attachment;filename="TEST.xls"  
  21.                 </param>  
  22.                 <param name="inputName">downLoadStream</param>  
  23.                 <param name="bufferSize">4096</param>  
  24.             </result>  
  25.         </action>  
  26.     </package>  
  27. </struts>  

 

注意:

contentType:要设置为下载类型为Excel,当然这些可以在Actoin里动态定义,想实现的具体再说。

contentDisposition:里面千万不要忘了attachment;不然可能会出一些问题,当然也许有的人不写。后面是下载的文件名,也可以在Action里定义。

inputName:真正执行下载的方法

bufferSize:缓冲区大小

3.写一个上传页面

Html代码  收藏代码
  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">      
  11.     <title>多文件Excel分析</title>  
  12.     <meta http-equiv="pragma" content="no-cache">  
  13.     <meta http-equiv="cache-control" content="no-cache">  
  14.     <meta http-equiv="expires" content="0">      
  15.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  16.     <meta http-equiv="description" content="This is my page">  
  17.   </head>    
  18.   <body>  
  19.     <center>  
  20.         <s:form action="doUpload" method="POST" enctype="multipart/form-data">  
  21.             <s:file name="upload" label="上传的文件1" />  
  22.             <s:file name="upload" label="上传的文件2" />  
  23.             <s:file name="upload" label="上传的文件3" />  
  24.             <s:file name="upload" label="上传的文件4" />  
  25.             <s:file name="upload" label="上传的文件5" />  
  26.             <s:file name="upload" label="上传的文件6" />  
  27.             <s:submit value="上   传"/>  
  28.         </s:form>  
  29.     </center>  
  30.   </body>  
  31. </html>  

 

注意:

里面使用了Struts2的标签,也可以直接使用Html标签

4.最关键的部分,写Action的类

Java代码  收藏代码
  1. package com.golden.action;  
  2.   
  3. import java.io.ByteArrayInputStream;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.InputStream;  
  8.   
  9. import org.apache.poi.hssf.usermodel.HSSFCell;  
  10. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  11. import org.apache.poi.hssf.usermodel.HSSFDateUtil;  
  12. import org.apache.poi.hssf.usermodel.HSSFRow;  
  13. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  15.   
  16. import com.opensymphony.xwork2.ActionSupport;  
  17.   
  18. import java.math.*;  
  19. import java.text.NumberFormat;  
  20.   
  21. @SuppressWarnings("serial")  
  22. public class StrutsFileUpload extends ActionSupport {  
  23.   
  24.     private File[] upload;// 实际上传文件  
  25.   
  26.     private String[] uploadContentType; // 文件的内容类型  
  27.   
  28.     private String[] uploadFileName; // 上传文件名  
  29.   
  30.     /** 
  31.      * 请求的Action 
  32.      */  
  33.     @Override  
  34.     public String execute() throws Exception {  
  35.         return "success";  
  36.     }  
  37.   
  38.     /** 
  39.      * 真正的下载方法 
  40.      *  
  41.      * @return 
  42.      * @throws Exception 
  43.      */  
  44.     @SuppressWarnings("deprecation")  
  45.     public InputStream getDownLoadStream() throws Exception {  
  46.         HSSFWorkbook wb = new HSSFWorkbook();  
  47.         // 设置一个靠右排放样式,如果需要其他样式自可以再定义一些  
  48.         HSSFCellStyle style = wb.createCellStyle();  
  49.         // style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  50.         style.setAlignment(HSSFCellStyle.ALIGN_RIGHT); // 在单元格中右排放  
  51.         try {  
  52.             for (int i = 0; i < upload.length; i++) {  
  53.                 File f = upload[i]; // 取得一个文件  
  54.                 FileInputStream is = new FileInputStream(f);  
  55.                 HSSFWorkbook wbs = new HSSFWorkbook(is);  
  56.                 // 根据读出的Excel,创建Sheet  
  57.                 HSSFSheet sheet = wb.createSheet(uploadFileName[i]);  
  58.                 // 一直取的是第一个Sheet,一定要注意,如果你要读取所有的Sheet,循环读取即可  
  59.                 HSSFSheet childSheet = wbs.getSheetAt(0);  
  60.                 // 循环读取Excel的行  
  61.                 for (int j = 0; j < childSheet.getLastRowNum(); j++) {  
  62.                     // 根据读取的行,创建要合并Sheet的行  
  63.                     HSSFRow r = sheet.createRow(j);  
  64.                     HSSFRow row = childSheet.getRow(j);  
  65.                     // 判断是否为空,因为可能出现空行的情况  
  66.                     if (null != row) {  
  67.                         // 循环读取列  
  68.                         for (int k = 0; k < row.getLastCellNum(); k++) {  
  69.                             // 根据读取的列,创建列  
  70.                             HSSFCell c = r.createCell(k);  
  71.                             HSSFCell cell = row.getCell(k);  
  72.                             // 将值和样式一同赋值给单元格  
  73.                             String value = "";  
  74.                             if (null != cell) {  
  75.                                 switch (cell.getCellType()) {  
  76.                                 case HSSFCell.CELL_TYPE_NUMERIC: // 数值型  
  77.                                     if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  78.                                         // 如果是Date类型则 ,获取该Cell的Date值  
  79.                                         value = HSSFDateUtil.getJavaDate(  
  80.                                                 cell.getNumericCellValue())  
  81.                                                 .toString();  
  82.                                     } else {// 纯数字,这里要判断是否为小数的情况,因为整数在写入时会被加上小数点  
  83.                                         String t = cell.getNumericCellValue()  
  84.                                                 + "";  
  85.                                         BigDecimal n = new BigDecimal(cell  
  86.                                                 .getNumericCellValue());  
  87.                                         // 判断是否有小数点  
  88.                                         if (t.indexOf(".") < 0) {  
  89.                                             value = n.intValue() + "";  
  90.                                         } else {  
  91.                                             // 数字格式化对象  
  92.                                             NumberFormat nf = NumberFormat  
  93.                                                     .getInstance();  
  94.                                             // 小数点最大两位  
  95.                                             nf.setMaximumFractionDigits(2);  
  96.                                             // 执行格式化  
  97.                                             value = nf.format(n.doubleValue());  
  98.                                         }  
  99.                                     }  
  100.                                     break;  
  101.                                 case HSSFCell.CELL_TYPE_STRING: // 字符串型  
  102.                                     value = cell.getRichStringCellValue()  
  103.                                             .toString();  
  104.                                     break;  
  105.                                 case HSSFCell.CELL_TYPE_FORMULA:// 公式型  
  106.                                     // 读公式计算值  
  107.                                     value = String.valueOf(cell  
  108.                                             .getNumericCellValue());  
  109.                                     break;  
  110.                                 case HSSFCell.CELL_TYPE_BOOLEAN:// 布尔  
  111.                                     value = " " + cell.getBooleanCellValue();  
  112.                                     break;  
  113.                                 /* 此行表示该单元格值为空 */  
  114.                                 case HSSFCell.CELL_TYPE_BLANK: // 空值  
  115.                                     value = " ";  
  116.                                     break;  
  117.                                 case HSSFCell.CELL_TYPE_ERROR: // 故障  
  118.                                     value = " ";  
  119.                                     break;  
  120.                                 default:  
  121.                                     value = cell.getRichStringCellValue()  
  122.                                             .toString();  
  123.                                 }  
  124.                             } else {  
  125.                                 value = " ";  
  126.                             }  
  127.                             c.setCellValue(value);  
  128.                             c.setCellStyle(style);  
  129.                         }  
  130.                     } else {  
  131.                         HSSFCell c = r.createCell(0);  
  132.                         c.setCellValue(" ");  
  133.                     }  
  134.                 }  
  135.             }  
  136.         } catch (Exception e) {  
  137.             e.printStackTrace();  
  138.         }  
  139.         // 这种写法不会产生临时文件,因为这里使用字节数组作为介质  
  140.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  141.         wb.write(os);  
  142.         byte[] content = os.toByteArray();  
  143.         InputStream is = new ByteArrayInputStream(content);  
  144.         return is;  
  145.     }  
  146.   
  147.     public File[] getUpload() {  
  148.         return upload;  
  149.     }  
  150.   
  151.     public void setUpload(File[] upload) {  
  152.         this.upload = upload;  
  153.     }  
  154.   
  155.     public String[] getUploadContentType() {  
  156.         return uploadContentType;  
  157.     }  
  158.   
  159.     public void setUploadContentType(String[] uploadContentType) {  
  160.         this.uploadContentType = uploadContentType;  
  161.     }  
  162.   
  163.     public String[] getUploadFileName() {  
  164.         return uploadFileName;  
  165.     }  
  166.   
  167.     public void setUploadFileName(String[] uploadFileName) {  
  168.         this.uploadFileName = uploadFileName;  
  169.     }  
  170.   
  171. }  

 

 这里要关注的地方太多,具体的代码里注释写的很清楚。

一定要注意的是要判断单元格的类型,特别是数字类型时,我根据自己的需求一定了一些处理。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics