struts2导出数据到excel并下载

首先这里导出excel数据使用的是apache的导出Microsoft office用的jar包,需要下载的直接去apache官网下载:http://poi.apache.org/download.html

需要导入的包有

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

下面是代码,使用的地方有注释

public String execute() throws Exception{

List<LinkedHashMap<String, String>> list = new ArrayList<LinkedHashMap<String,String>>();
         for (int i = 0; i <= 9; i++) {
             LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
             map.put("日期范围", "20140102-20140109");
             map.put("工号", "2008"+i);
             map.put("姓名", "张星");
             map.put("职位", "组长");
             map.put("组别", "1组");
             map.put("办公地址", "外经贸");
             list.add(map);
         }

return createExcelSheet(“工作信息报表”,list);

}

private String createExcelSheet(String excelName,List<LinkedHashMap<String, String>> excelData) {
        //创建一个webbook,对应一个Excel文件 
        HSSFWorkbook wb = new HSSFWorkbook(); 
        //在webbook中添加一个sheet,对应Excel文件中的 sheet 
        HSSFSheet sheet = wb.createSheet(excelName); 
        //在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制 
        HSSFRow row0 = sheet.createRow(0); 
        //创建单元格样式:居中 
        HSSFCellStyle style = wb.createCellStyle(); 
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
        //创建表头单元格,并设置样式 

        LinkedHashMap<String, String> row0Data = excelData.get(0);
        short index = 0;
        for (Iterator<String> it = row0Data.keySet().iterator(); it.hasNext();) {
            String key = it.next();
            HSSFCell cell = row0.createCell(index); 
            cell.setCellValue(key); 
            cell.setCellStyle(style); 
            index ++;
        }

        //写入实体数据,遍历数据即可 
        for (int i=0;i<excelData.size();i++) {
            HSSFRow row = sheet.createRow(i+1);
            LinkedHashMap<String, String> columnMap = excelData.get(i);
            short j = 0;
            for (Iterator<String> it = columnMap.values().iterator(); it.hasNext();) {
                 String val = it.next();
                 row.createCell(j).setCellValue(val);
                 j++;
            }
        }
       

        //第七步,将文件存到流中 
        ByteArrayOutputStream os = new ByteArrayOutputStream(); 
        try {
            wb.write(os);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        byte[] fileContent = os.toByteArray(); 
        ByteArrayInputStream is = new ByteArrayInputStream(fileContent); 

        excelStream = is;             //文件流 
       
        excelFileName = “report.xls”; //设置下载的文件名 


        return "success";
    }

这只是一个简单的excel应用实例,其它的均可以参照框架使用相应的api

你可能感兴趣的:(struts2导出数据到excel并下载)