excel的导出(贴程序)

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.mln.realtime.beans.PowerHisData;
import com.mln.report.CellMetaData;
import com.mln.report.ExportExcelAction;

public class ExportRealtimePowerDataAction extends ExportExcelAction {
    private Sheet sheet1;
    private Workbook wb; // Excel工作簿
    private CellStyle style1 ;   // 日期样式
    private CellStyle style2 ;   // 自动换行左缩进样式
    private CellStyle style3 ;   // 普通样式
    public static int temp=0;
    private static Logger logger = Logger.getLogger(ExportGWMeterHDataReportAction.class);
    @Override
    public Map<String, CellMetaData> getReportData() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String execute() {
        // TODO Auto-generated method stub
        this.setReportId("RPT54");
        //excel文件名称
        this.setReportName("5分钟负荷统计表.xls");
        try {
            wb = new HSSFWorkbook();
            //    sheet1 = wb.getSheetAt(0);
            //创建样式
            style1 = wb.createCellStyle();
            style2 = wb.createCellStyle();
            style3 = wb.createCellStyle();
            //将数据按月存数在map集合中key为月份 value为这个月的所有数据
            Map<Integer, List<PowerHisData>> powMap = separateByMonth();
            //按月循环,每个月创建一个工作表
            for(int j=1;j<=12;j++){
                //创建工作表,并命名
                Sheet sheet = wb.createSheet(j+"月");
                //创建工作表头信息
                createExcelHead(sheet,j);
                //得到当月的所有数据
                List<PowerHisData> list = powMap.get(j);
                //为工作表填充数据
                createExcelColumnNumOne(sheet,j,list);
            }
            // 6.输出报表
            this.outputExcel(wb);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            this.getRequest().setAttribute(this.ERRMSG, e);
            logger.error("" + e.getMessage());
            return this.ERROR;
        }
        return null;
    }
    private void createContext() {
        String hql = "from PowerHisData";
        List<PowerHisData> list = daoSrv.findByHql(hql);
        
    }
    /**
     * 将从数据库中查出的数据按月分开
     * @return以月份为key,每月的数据位value的map集合
     */
    public Map<Integer ,List<PowerHisData>> separateByMonth(){
        String hql = "from PowerHisData ";
        List<PowerHisData> list = daoSrv.findByHql(hql);
        Map<Integer, List<PowerHisData>> powMap = new TreeMap<Integer, List<PowerHisData>>();
        //按月将数据存储到map集合中key为月份,value为当月的数据
        for(int j=1;j<=12;j++){
             List<PowerHisData> powList = new ArrayList<PowerHisData>();
             for(int i=0;i<list.size();i++){
                 Date date = list.get(i).getRealtime();
                 Calendar cal = Calendar.getInstance();
                 cal.setTime(date);
                 int month = cal.get(Calendar.MONTH)+1;
                 if(month==j){
                     powList.add(list.get(i));
                 }
            }
             powMap.put(j, powList);
        }
        
        return powMap;
    }
    /**
     * 设置每个工作表中的标头信息(第一行)
     * @param sh 当前工作表
     * @param i 月份
     */
    public void createExcelHead(Sheet sh,int i){
         HSSFHeader header = (HSSFHeader) sh.getHeader();
         header.setCenter("五分钟负荷统计");
         //创建一行
         HSSFRow headerRow = (HSSFRow) sh.createRow((short) 0);
         Calendar c = Calendar.getInstance();
         int year = c.get(Calendar.YEAR);
         c.set(Calendar.YEAR, year);
        //注意 一月为 0
         c.set(Calendar.MONTH, i-1);
         //当月总共有多少天
         int days = c.getActualMaximum(Calendar.DAY_OF_MONTH);
         //设置第一行的标头信息headerCell在这里为第一行的第一列
         HSSFCell headerCell = headerRow.createCell(0);
         headerCell.setCellValue("时间");
         setStyleColor(headerCell);
         //格式化时间
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        //设置为当月的第一天
         c.set(Calendar.DAY_OF_MONTH, 1);
         for(int j=1;j<(days+1);j++){
             //headerCell在此为从当月第一天循环到最后一天
             headerCell = headerRow.createCell(j);
             headerCell.setCellValue(sdf.format(c.getTime()));
             //添加样式
             setStyleColor(headerCell);
             //天数加1
             c.add(Calendar.DAY_OF_MONTH, 1);
         }
    }
    /**
     * 为excel填充数据
     * @param sh 当前工作表
     * @param i 当前月份
     * @param list 当前月的数据
     */
    public void createExcelColumnNumOne(Sheet sh,int i,List<PowerHisData> list){
        Calendar c = Calendar.getInstance();
        //取得当前年
        int year = c.get(Calendar.YEAR);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        c.set(Calendar.YEAR, year);
        //注意 一月为 0
        c.set(Calendar.MONTH, i-1);
        //获取当前月的天数
        int days = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        Calendar cal = Calendar.getInstance();
        //设置为当月的第一天开始
        cal.set(Calendar.MINUTE, 0);
        //设置为24小时制,并从00:00开始
        cal.set(Calendar.HOUR_OF_DAY, 00);
        for(int j=1;j<289;j++){
            HSSFRow row = (HSSFRow) sh.createRow(j);
            //从00:00开始每次加5分钟设置为第一列的值
            String str = sdf.format(cal.getTime());
            String strs[] = str.split(" ");
            String s = strs[1].substring(0, 5);
            HSSFCell cell = row.createCell(0);
            cell.setCellStyle(style3);  //添加样式
            cell.setCellValue(s);
            
            //循环这个月的每一天,每一天创建一列
            for(int d=1;d<=days;d++){
                cell = row.createCell(d);
                cell.setCellStyle(style3);
                //在当月的所有信息中查找符合条件的数据 条件为:当月的第几天+该数据的Finetime是否与第一列的数据相等(00:00-23:55)+该数据的月份是否相等
                for(int l=0;l<list.size();l++){
                    Date date = list.get(l).getRealtime();
                    int month = findMonthOfDate(date);
                    //条件为:当月的第几天+该数据的Finetime是否与第一列的数据相等(00:00-23:55)+该数据的月份是否相等
                    if(findDayOfDate(date)==d && s.equals(list.get(l).getFinetime()) && month==i){
                        //找到数据则写入到相应的单元格内
                        cell.setCellValue(list.get(l).getPower());
                    }
                }
                //如果没有符合的数据则单元格内默认为0
                double cel = cell.getNumericCellValue();
                if(cel==0){
                    cell.setCellValue(0);
                }
            }
            //加5分钟
            cal.add(Calendar.MINUTE, 5);
            
        }
 
        
    }
    /**
     * 得到传入日期中的天
     * @param date 传入的日期
     * @return 那一天
     */
    public int findDayOfDate(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        return day;
    }
    /**
     * 得到传入日期中的天
     * @param date 传入的日期
     * @return 那一天
     */
    public int findMonthOfDate(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int month = cal.get(Calendar.MONTH);
        return month+1;
    }
    private void setStyleColor(HSSFCell cell){
        CellStyle styleColor = wb.createCellStyle();
        styleColor.setFillForegroundColor((short)1);
        HSSFFont font = (HSSFFont) wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        styleColor.setFont(font);
        cell.setCellStyle(styleColor);
    }

    //日期格式
    private CellStyle setStyle1(){
        //style1.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
        style1.setWrapText(true);
        style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style1.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
        style1.setBottomBorderColor(HSSFColor.BLACK.index);
        style1.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
        style1.setLeftBorderColor(HSSFColor.BLACK.index);
        style1.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
        style1.setRightBorderColor(HSSFColor.BLACK.index);
        style1.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
        style1.setTopBorderColor(HSSFColor.BLACK.index);
        return style1;
    }
    
    //左缩进大文本格式
    private CellStyle setStyle2(){
        style2.setWrapText(true);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        style2.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
        style2.setBottomBorderColor(HSSFColor.BLACK.index);
        style2.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
        style2.setLeftBorderColor(HSSFColor.BLACK.index);
        style2.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
        style2.setRightBorderColor(HSSFColor.BLACK.index);
        style2.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
        style2.setTopBorderColor(HSSFColor.BLACK.index);
        return style2;
    }
    
    //普通格式
    private CellStyle setStyle3(){
        style3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style3.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style3.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
        style3.setBottomBorderColor(HSSFColor.BLACK.index);
        style3.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
        style3.setLeftBorderColor(HSSFColor.BLACK.index);
        style3.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
        style3.setRightBorderColor(HSSFColor.BLACK.index);
        style3.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
        style3.setTopBorderColor(HSSFColor.BLACK.index);
        return style3;
    }
    /**
     * 设置字体
     * @param wb
     * @return
     */
    public Font createFont(Workbook wb){
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeight((short)4);
        return font;
    }

    public Sheet getSheet1() {
        return sheet1;
    }

    public void setSheet1(Sheet sheet1) {
        this.sheet1 = sheet1;
    }

    public Workbook getWb() {
        return wb;
    }

    public void setWb(Workbook wb) {
        this.wb = wb;
    }

}

 

 

 

上面是程序

这个是程序中用到的表的建表语句

CREATE TABLE dbo.POWERHISDATA
    (
    ID CHAR (32) NOT NULL,
    REALTIME DATETIME NOT NULL,
    FINETIME VARCHAR (5) NOT NULL,
    POWER DECIMAL (16,2) NOT NULL,
    CONSTRAINT PK_POWERHISDATA PRIMARY KEY (ID)
    )

 

 

 

 

导出后的样子

由于自己也是第一次导出excel,做的也不是很好 ,上面查数据和输出excel时用到了公司的框架里通用的,所以这一块还要自己在写一下。

posted @ 2011-11-09 10:19  村里的树  阅读(455)  评论(0编辑  收藏  举报