用struts2把数据导出成一个Excel表 要到两个包struts2-core-2.0.9.jar和jxl.jar

public    void list()

 {

HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
 HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);

List<String []> datalist = new ArrayList<String[]>();

List<UserConsumeBean> consumelist1 = userService.consumeDatelist(数据库里取出数据);

String [] str1 = new String [1] ;
        str1[0]="日期";

datalist.add(str1);

for(Iterator<UserConsumeBean> iter = consumelist1.iterator();iter.hasNext();)
            {
                String [] str = new String [1] ;
                UserConsumeBean  bean = iter.next();
                str[0] = bean.getDayTimes();

datalist.add(str);
            }

DoPost.doPost(request, response,datalist, 1);

}

import org.apache.struts2.ServletActionContext;

public class DoPost {

//datalist是要导出的数据,colsNum是有几列
    public static void doPost(HttpServletRequest request,
            HttpServletResponse response, List<String[]> datalist, int colsNum)
            throws ServletException, IOException {

        ServletOutputStream out = null;
        FileInputStream fileInputStream = null;
        File file = null;

        try {
            response.setContentType("text/html;charset=UTF-8");
            out = response.getOutputStream();
            String filePath = ServletActionContext.getRequest().getRealPath(
                    "/file")
                    + "\\";
            String fileName = "data.xls";
            // 数据取的列数
            // int colsNum = Integer.parseInt(request.getParameter("closNum"));
            System.out.println("colsNum: " + colsNum);
            // Map map = UserAction.dataMap;
            // List<String []> datalist = (List<String []>)map.get("dataList");
            boolean flag = ExportExcel.createExcel(filePath + fileName,
                    datalist, colsNum);
            System.out.println("DownloadFile filepath:" + filePath);
            System.out.println("DownloadFile fileName:" + fileName);
            file = new File(filePath + fileName);

            if (!file.exists()) {
                System.out.println(file.getAbsolutePath() + " 文件不存在!");
                return;
            }
            // 读取文件流
            fileInputStream = new java.io.FileInputStream(file);
            // 下载文件
            // 设置响应头和下载保存的文件名
            if (fileName != null && fileName.length() > 0) {
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + fileName + "");
                if (fileInputStream != null) {
                    int filelen = fileInputStream.available();
                    System.out.println("---------filelen="+filelen);
                    // 文件太大时内存不能一次读出,要循环
                    byte a[] = new byte[filelen];
                    fileInputStream.read(a);
                    out.write(a);
                }

//                fileInputStream.close();
//                out.close();
            }
        } catch (Exception ex) {

            ex.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (out != null) {
                out.close();
            }
        }

    }

}



public class ExportExcel {


    private static jxl.write.Number number;


    /**
     * @param args
     */
    public static void main(String[] args) {
        //createExcel(null, null);
        
        try
        {
            File f=new File("D:/recharge.xls");
            readExl("D:/recharge.xls");
//            f.createNewFile();
//            writeExcel(new FileOutputStream(f));
        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }


    public static boolean createExcel(String filePath , List<String []> list ,int  colsNum) {
        WritableWorkbook wwb = null;
        try
        {
            //filePath = "D:/game_manager/file/data.xls";
            System.out.println("文件路径:"+filePath);
            // 首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
            wwb = Workbook.createWorkbook(new File(filePath));
        
            if (wwb != null)
            {
                // 创建一个可写入的工作表
                // Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置
                WritableSheet ws = wwb.createSheet("sheet1", 0);
    
                //int colsNum = ws.getColumns();
                Label label1 = null;
                //下面开始添加单元格
                for (int i = 0; i < list.size(); i++)
                {        
                    String [] str = (String [])list.get(i);
                    for(int j = 0; j < colsNum; j++)
                    {
                        // 这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行
                        System.out.println(j+"..."+i+"..."+str[j]);
                        ws.setColumnView(j, 20);
                        if(str[j]!=null&& str[j].matches("\\d+\\.?\\d+$|^\\d+")){
                            number = new jxl.write.Number(j, i, Double.valueOf(str[j]));
                            // 将生成的单元格添加到工作表中
                            ws.addCell(number);
                        }else{
                            label1 = new Label(j, i, str[j]);
                            // 将生成的单元格添加到工作表中
                            ws.addCell(label1);
                        }
                        
                        
                    }        
                }

            }
                // 从内存中写入文件中
                wwb.write();
                // 关闭资源,释放内存
                //wwb.close();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally
            {
                try
                {
                    if(wwb != null)
                    {            
                        wwb.close();
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    
    /**
      *
      * 读取excel
      * @param file 文件路径
      * @param i 第i个工作表。
      */
     public static List<String []> readExl(String file)
     {
         Workbook book = null;
         List<String []> dataList = new java.util.ArrayList<String[]>();
         String [] arr = null;
          try
          {
               book = Workbook.getWorkbook(new File(file));
               //获的第一个工作表对象
               jxl.Sheet sheet = book.getSheet(0);
               System.out.println("sheet=="+sheet);
               int col = sheet.getRows();
               System.out.println("size: "+col);
               //得到第一列第一行的单元格
               for(int i = 0; i < col; i++)
               {
                   
                   arr = new String[2];
                   jxl.Cell cell = sheet.getCell(0, i);
                   jxl.Cell cell1 = sheet.getCell(1, i);
                   String result = cell.getContents();
                   String result1 = cell1.getContents();
                   arr[0] = result;
                   arr[1] = result1;
                   System.out.println(arr[0]+"..."+arr[1]);
                   dataList.add(arr);
               }        
        
          } catch (Exception e) {
               System.out.println(e);
          }finally
          {
              if(book != null)
              {
                  book.close();
              }
          }
          return dataList;

     }


如果点击导出按钮然后又返回到当前页面注意超时时间,不然会报IO异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值