在Struts中利用Jxl对Excel的导入导出

本文介绍了一个使用Struts框架实现的Excel模板下载及上传验证的方法。具体包括:通过Struts提供Excel模板下载,利用jxl库读取并验证上传的Excel文件内容。此方案适用于需要收集标准化表格数据的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:  1,提供客户填写数据的EXCEL模板下载. 2,对客户上传的EXCEL中的数据进行效验
技术:  1,Struts做web的表示层,提供上传,下载 2,利用jxl 对 EXCEL 进行操作.
代码:  EXCEL模板的实现.

一,struts中的action提供模板下载:action

Java代码 复制代码
  1. /**  
  2.   *  模版下载页面  
  3.   *  */    
  4. public   class   ExportTemplateAction  extends   Action  {    
  5.    
  6.         public   ActionForward  execute(ActionMapping  mapping,  ActionForm  form,    
  7.                         HttpServletRequest  request,  HttpServletResponse  response)    
  8.                         throws   Exception  {    
  9.                 javax.servlet.http.HttpSession  session=request.getSession();    
  10.                 HMITSession  hmitsession=  (HMITSession)session.getAttribute( " hmitsession" );    
  11.                 //获取企业代码,业务规则,用于设置文件目录    
  12.                 String  entCode=hmitsession.getEntCode();    
  13.                 //设置文件路径,业务规则设置了存于服务器上 的文件路径    
  14.                 File  templateFile  =  new   File(AppConst.getDownloadFileDirectory(entCode)+File.separator+ " Template.xls" );    
  15.                    
  16.                 if (!templateFile.exists()){    
  17.                         //设置excel的标题,假设只有一行标题    
  18.                         String  []titles={ " 司机编号(必填)" , " 司机名称(必填)" , " 驾照" , " 身份证" , " 手机" } ;    
  19.                         //设置sheet名称    
  20.                         String  sheetName= " 司机数据" ;    
  21.                         //获取excel文件    
  22.                         templateFile=Util.getExcel(templateFile,  sheetName,  titles);    
  23.                 }          
  24.                 //写入response    
  25.                 Util.downLoadData(response,  templateFile,  " Template.xls" );    
  26.                 return   null ;    
  27.         }    
/** * 模版下载页面 * */public class ExportTemplateAction extends Action {
 public ActionForward execute(ActionMapping mapping, ActionForm form,                    HttpServletRequest request, HttpServletResponse response)                       throws Exception {
              javax.servlet.http.HttpSession session=request.getSession();
            HMITSession hmitsession= (HMITSession)session.getAttribute("
hmitsession"
);
              //获取企业代码,业务规则,用于设置文件目录          String entCode=hmitsession.getEntCode();
                //设置文件路径,业务规则设置了存于服务器上的文件路径             File templateFile = new File(AppConst.getDownloadFileDirectory(entCode)+File.separator+"
Template.xls"
);
                         if(!templateFile.exists()){
                     //设置excel的标题,假设只有一行标题                   String []titles={
"
司机编号(必填)"
,"
司机名称(必填)"
,"
驾照"
,"
身份证"
,"
手机"
}
;
                        //设置sheet名称                     String sheetName="
司机数据"
;
                        //获取excel文件                     templateFile=Util.getExcel(templateFile, sheetName, titles);
            }
                       //写入response            Util.downLoadData(response, templateFile, "
Template.xls"
);
              return null;
    }


  二,获取EXCEL文件的工具类
Java代码 复制代码
  1. public   class   Util  {    
  2.                   /**  
  3.                   *  @param    需要校验的字符串  
  4.                   *  @return    true为null,false  为非null  
  5.                   *  */    
  6.                 public   static   boolean   checkNull(String  temp){    
  7.                         return   temp== null   ?  true : false ;    
  8.                 }    
  9.                 /**  
  10.                   *  @param  temp  
  11.                   *  @return  将null  返回为" " ;  
  12.                   *  */    
  13.                 public   static   String  notNull(String  temp){    
  14.                         return   checkNull(temp)?  " " :  temp;    
  15.                 }    
  16.    
  17.    
  18.                    
  19.                 /**  
  20.                   *  创建一个规定格式的excel,第一行为标题行,每个标题为一个cell  
  21.                   *  @param  templateFile  一个文件  
  22.                   *  @param  sheetName  excel的sheet的名字  
  23.                   *  @param  titles  标题列  
  24.                   *  */    
  25.                 public   static   File  getExcel(File  templateFile,String  sheetName,String  []titles)    throws   Exception{    
  26.                         //根据现有文件创建一个可写excel    
  27.                         WritableWorkbook  ww  =  Workbook.createWorkbook(templateFile);    
  28. /**在这里可以设置编码格式  
  29.                 WorkbookSettings  setting=new  WorkbookSettings();  
  30.                 java.util.Locale  locale  =  new  java.util.Locale(" zh" ," CN" );      
  31.                 setting.setLocale(locale);  
  32.                 setting.setEncoding(" UFT-8" );  
  33.                 */    
  34.                       //创建一个可写的sheet文件 createSheet(sheetName,0),sheet名称,0代表第几个sheet    
  35.                         WritableSheet  ws  =ww.createSheet(sheetName, 0 );    
  36.                         //字体设置    
  37.                         WritableFont  arial10ptBold  =  new   WritableFont  (WritableFont.ARIAL,  10 ,  WritableFont.NO_BOLD);    
  38.                         arial10ptBold.setColour(Colour.RED);    
  39.                         //设置格式,这里可以根据不同需要,设置多个 格式,需要WritableFont进行构造    
  40.                         WritableCellFormat  arial10BoldFormat  =  new   WritableCellFormat  (arial10ptBold);    
  41.                         //这里可以设置字体对齐方式等等    
  42.                         arial10BoldFormat  .setAlignment(jxl.format.Alignment.CENTRE);          
  43.                         //定义单元格    
  44.                         Label    cell=  null ;    
  45. /**合并单元格  
  46.                 ws.mergeCells(0,  0,  8,  0);  
  47.                 cell=new  Label(0,0," 产品信息" ,fontCenter);  
  48.                 ws.addCell(cell);  
  49.                 */    
  50.                            
  51.                         for   ( int   i  =  0 ;   i  <   titles.length;   i++)  {    
  52. //第一个参数为列,第二个参数为 行,第三个参数为cell的内容,第四个为字体的格式    
  53.                                 cell= new   Label(i, 0 ,titles[i],arial10BoldFormat);    
  54.                                 ws.addCell(cell);    
  55.                         }    
  56.                         ww.write(); //写入到当前文件    
  57.                         ww.close();    
  58.                         ww= null ;    
  59.                         return   templateFile;    
  60.    
  61.                 }    
  62.            
  63.         }    
  64. /**  
  65.           *  下载设置  
  66.           *  */    
  67.         public   static     void   downLoadData(HttpServletResponse  response,File  returnFile,String  uploadedFileName){    
  68.                 response.setHeader( " Content-disposition" , " attachment;   filename=" +uploadedFileName);    
  69.                 response.setHeader( " Content-Type" " application/octet-stream" );    
  70.                    
  71.                 BufferedInputStream  bis  =  null ; //读excel    
  72.                 BufferedOutputStream  bos  =  null ; //输出    
  73.                    
  74.                 try {    
  75.                         //读取excel文件    
  76.                         bis  =  new   BufferedInputStream( new   FileInputStream(returnFile));    
  77.                         //写入response的输出流中    
  78.                         bos= new   java.io.BufferedOutputStream(response.getOutputStream());    
  79.                         byte []  buff  =  new   byte [ 2048 ]; /*设置缓存*/    
  80.                         int   bytesRead;    
  81.                         while (- 1 !=  (bytesRead  =  bis.read(buff,  0 ,  buff.length))){    
  82.                                 bos.write(buff,  0 ,  bytesRead);    
  83.                         }    
  84.                 } catch (Exception  e){    
  85.                         e.printStackTrace();    
  86.                 } finally {    
  87.                         if   (bis  !=  null )    
  88.                                 try   {    
  89.                                         bis.close();    
  90.                                 }   catch   (IOException  e)  {    
  91.                                         e.printStackTrace();    
  92.                                 }    
  93.                         if   (bos  !=  null )    
  94.                                 try   {    
  95.                                         bos.close();    
  96.                                 }   catch   (IOException  e)  {    
  97.                                         e.printStackTrace();    
  98.                                 }    
  99.                 }    
  100.         }    
public class Util {
         /**             * @param  需要校验的字符串              * @return  true为null,false 为非null               * */           public static boolean checkNull(String temp){
                   return temp==null ? true:false;
         }
               /**              * @param temp           * @return 将null 返回为"
"
;
          * */           public static String notNull(String temp){
                      return checkNull(temp)? "
"
: temp;
               }
                               /**              * 创建一个规定格式的excel,第一行为标题行,每个标题为一个cell            * @param templateFile 一个文件              * @param sheetName excel的sheet的名字               * @param titles 标题列             * */           public static File getExcel(File templateFile,String sheetName,String []titles)  throws Exception{
                      //根据现有文件创建一个可写excel                     WritableWorkbook ww = Workbook.createWorkbook(templateFile);
/**在这里可以设置编码格式              WorkbookSettings setting=new WorkbookSettings();
                java.util.Locale locale = new java.util.Locale("
zh"
,"
CN"
);
              setting.setLocale(locale);
              setting.setEncoding("
UFT-8"
);
           */           //创建一个可写的sheet文件createSheet(sheetName,0),sheet名称,0代表第几个sheet                       WritableSheet ws =ww.createSheet(sheetName,0);
                  //字体设置                  WritableFont arial10ptBold = new WritableFont (WritableFont.ARIAL, 10, WritableFont.NO_BOLD);
                   arial10ptBold.setColour(Colour.RED);
                    //设置格式,这里可以根据不同需要,设置多个格式,需要WritableFont进行构造                     WritableCellFormat arial10BoldFormat = new WritableCellFormat (arial10ptBold);
            //这里可以设置字体对齐方式等等            arial10BoldFormat .setAlignment(jxl.format.Alignment.CENTRE);
                         //定义单元格                     Label  cell= null;
/**合并单元格              ws.mergeCells(0, 0, 8, 0);
              cell=new Label(0,0,"
产品信息"
,fontCenter);
          ws.addCell(cell);
               */                                              for (int i = 0;
 i <
 titles.length;
 i++) {
//第一个参数为列,第二个参数为行,第三个参数为cell的内容,第四个为字体的格式                           cell=new Label(i,0,titles[i],arial10BoldFormat);
                                ws.addCell(cell);
                       }
                       ww.write();
//写入到当前文件                    ww.close();
                     ww=null;
                        return templateFile;
            }
               }
/**     * 下载设置  * */   public static  void downLoadData(HttpServletResponse response,File returnFile,String uploadedFileName){
         response.setHeader("
Content-disposition"
,"
attachment;
 filename="
+uploadedFileName);
             response.setHeader("
Content-Type"
, "
application/octet-stream"
);
                         BufferedInputStream bis = null;
//读excel         BufferedOutputStream bos = null;
//输出                            try{
                    //读取excel文件                     bis = new BufferedInputStream(new FileInputStream(returnFile));
                 //写入response的输出流中                       bos=new java.io.BufferedOutputStream(response.getOutputStream());
                       byte[] buff = new byte[2048];
/*设置缓存*/                   int bytesRead;
                  while(-1!= (bytesRead = bis.read(buff, 0, buff.length))){
                               bos.write(buff, 0, bytesRead);
                  }
               }
catch(Exception e){
                    e.printStackTrace();
            }
finally{
                       if (bis != null)                                try {
                                   bis.close();
                            }
 catch (IOException e) {
                                       e.printStackTrace();
                            }
                       if (bos != null)                                try {
                                   bos.close();
                            }
 catch (IOException e) {
                                       e.printStackTrace();
                            }
               }
       }


  三,文件上传
Java代码 复制代码
  1. public   class   ExportAction  extends   Action  {    
  2.    
  3.         public   ActionForward  execute(ActionMapping  mapping,  ActionForm  form,    
  4.                         HttpServletRequest  request,  HttpServletResponse  response)    
  5.                         throws   Exception  {    
  6.                    
  7.                 HttpSession  session=  request.getSession();    
  8.                 HMITSession  hmitsession=  (HMITSession)session.getAttribute( " hmitsession" );    
  9.                    
  10.                 //用户上传数据信息是否正确的标志位    
  11.                 boolean   flag= true ;    
  12.                    
  13.                 ChauffeurExportForm  cef=(ChauffeurExportForm)  form;    
  14.                 /**  
  15.                   *  获取提交表单信息  
  16.                   *  */    
  17.                 //获取上传文件    
  18.                 InputStream  uploadedFileStream  =cef.getUploadFile().getInputStream();    
  19.                 String  ansy  =  ChauffeurUtil.notNull(request.getParameter( " asynchronism" )); /*如果需要开启多线程处理  则为1*/    
  20.                 String  email=  ChauffeurUtil.notNull(request.getParameter( " emailAddress" )); /*开启线程发送邮件*/    
  21.                    
  22.                 //上传文件名称    
  23.                 String  fileName=getTempExcelName(cef.getUploadFile().getFileName());    
  24.                 //写入上传文件夹目录+名称    
  25.                 String  uploadedFileName=AppConst.getUploadFileDirectory(hmitsession.getEntCode())+File.separator+fileName;    
  26.                 //获取到excel对象    
  27.                 Workbook  workbook  =  Workbook.getWorkbook(uploadedFileStream);    
  28.                 //将上传文件放置上传文件目录中    
  29.                 writeExcel(workbook,uploadedFileName);    
  30.                    
  31.                 //写入文件    
  32.                 File  returnFile  =  new     File(AppConst.getUploadTempDirectory(hmitsession.getEntCode())+File.separator+fileName);    
  33.                 //写入临时文件    
  34.                 WritableWorkbook  rww  =  Workbook.createWorkbook(returnFile,workbook);    
  35.                 //从临时文件中取得sheet    
  36.                 Sheet  sheet=  workbook.getSheet( 0 );    
  37.                 //设置字体    
  38.                 WritableFont  arial10ptBold  =  new   WritableFont  (WritableFont.ARIAL,  10 ,  WritableFont.NO_BOLD);    
  39.                 arial10ptBold.setColour(Colour.RED); //红色错误字体    
  40.                 WritableCellFormat  arial10BoldFormat  =  new   WritableCellFormat  (arial10ptBold);    
  41.                    
  42.                 /**  
  43.                   *  以下为业务判断和操作  
  44.                   *  Label为一个单元格  
  45.                   *  sheet.getRows  获取所有行  
  46.                   *  rww.getSheet(0).addCell(cell)  将cell放入对应的sheet中  
  47.                   *   
  48.                   *  获取关系应为    sheet(index)  --> sheet(index).getCell(col,row);  
  49.                   *  */    
  50.                 Label    cell=  null ;    
  51.                 StringBuffer  error= new   StringBuffer( " " );    
  52.                 for   ( int   i  =  0 ;   i  < sheet.getRows()  ;   i++)  {    
  53.                         error.delete( 0 ,  error.length());    
  54.                         String  chauffeurNo=sheet.getCell( 0 ,  i).getContents();    
  55.                         String  chauffeurName=sheet.getCell( 1 ,  i).getContents();    
  56.                         if (chauffeurNo.equals( " " )){    
  57.                                 cell= new   Label( 8 ,i,error.append( " ~司机编号没有填写" ).toString(),arial10BoldFormat);    
  58.                                 rww.getSheet( 0 ).addCell(cell);    
  59.                                 flag= false ;    
  60.                         }    
  61.                         if (chauffeurName.equals( " " )){    
  62.                                 cell= new   Label( 8 ,i,error.append( " ~司机名称没有填写" ).toString(),arial10BoldFormat);    
  63.                                 rww.getSheet( 0 ).addCell(cell);    
  64.                                 flag= false ;    
  65.                         }    
  66.                            
  67.                 }    
  68.                 //  -------------------------------------若干业务逻辑操作省略    
  69.                 uploadedFileStream.close();    
  70.                 uploadedFileStream= null ;    
  71.                 rww.write();            
  72.                 rww.close();    
  73.                 rww= null ;    
  74.                 //记录日志    
  75.                 if (flag)  Util.setLog(request,hmitsession, " wms_car_dirver_add" , " 司机批量新增" );    
  76.                 //异步    
  77.                 if (ansy.equals( " 1" )){    
  78.                         //异步处理    
  79.                         AsynchronousHandle  thread  =  new   AsynchronousHandle( this .getServlet().getServletContext(),    
  80.                                                                                                 email,returnFile,flag,uploadedFileName);    
  81.                         thread.start();    
  82.                 } else {    
  83.                         //同步处理    
  84.                         if (flag){ //无错误    
  85.                                 request.setAttribute( " flag" " 1" );    
  86.                                 request.setAttribute( " msg" " 更新顺利完成" );    
  87.                         } else { //出现错误数据    
  88.                                 request.setAttribute( " flag" " 2" );    
  89.                                 request.setAttribute( " msg" " 上传的数据有错误!请检验核对后再次进行上传" );    
  90.                                 //设置下载    
  91.                                 Util.downLoadData(  response,returnFile  ,  cef.getUploadFile().getFileName());    
  92.                                 return   null ;    
  93.                         }    
  94.                 }    
  95.                    
  96.                 return   null ;    
  97.         }    
  98.            
  99.         public   static   String  getTempExcelName(String  excelName){    
  100.                 String  time  =  HMITStr.encodeHTML( new   Date(), " yyyyMMddHHmmssSS" ); //获取服务器时间    
  101.                 int   posi  =  excelName.lastIndexOf( " ." );    
  102.                 String  fileName=excelName.substring( 0 ,posi)+time+excelName.substring(posi);    
  103.                 return   fileName;    
  104.         }    
  105.            
  106.         public   static   void   writeExcel(Workbook  workbook,String  uploadedFileName)  throws   Exception,  IOException{    
  107.                 WritableWorkbook  ww  =  Workbook.createWorkbook(  new   File(uploadedFileName),workbook);    
  108.                 ww.write();    
  109.                 ww.close();    
  110.                 ww= null ;    
  111.         }    
  112.    
  113. }    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yylei1019

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值