poi测试代码

package aurora.plugin.poi;

import aurora.database.IResultSetConsumer;
import aurora.database.service.SqlServiceContext;
import aurora.i18n.ILocalizedMessageProvider;
import aurora.i18n.IMessageProvider;
import aurora.plugin.export.MergedHeader;
import aurora.service.ServiceContext;
import aurora.service.ServiceInstance;
import aurora.service.http.HttpServiceInstance;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import uncertain.composite.CompositeMap;
import uncertain.composite.DynamicObject;
import uncertain.event.IContextAcceptable;
import uncertain.logging.ILogger;
import uncertain.logging.LoggingContext;
import uncertain.ocm.IObjectRegistry;

public class Excel2007Output
  implements IResultSetConsumer, IContextAcceptable
{
  CellStyle headstyle;
  CellStyle bodystyle;
  Map<Integer, CellStyle> styleMap = new HashMap();

  Map<Integer, CompositeMap> columnMap = new TreeMap();
  Map<Integer, Map<Integer, String>> headMap = new TreeMap();
  Map<String, Object> rowMap;
  int headLevel;
  ServiceContext ServiceContext;
  ILogger mLogger;
  IObjectRegistry mObjectRegistry;
  ILocalizedMessageProvider localMsgProvider;
  IExcelBean excelBean;
  Workbook wb;
  Sheet sheet;
  CreationHelper creationHelper;
  CellStyle bodyStyle;
  String fileName;
  String fileType;
  int sheetNum = 0;

  public final String XML_ENCODING = "UTF-8";
  public static final String KEY_DATA_TYPE = "datatype";
  public static final String KEY_DATA_TYPE_NUMBER = "Number";
  public static final String KEY_DATA_TYPE_STRING = "String";
  public static final String KEY_DATA_FORMAT = "dataFormat";

  public Excel2007Output(IObjectRegistry registry)
  {
    this.mObjectRegistry = registry;
    this.mLogger = 
      LoggingContext.getLogger("aurora.plugin.poi", this.mObjectRegistry);
  }

  void initialization() {
    IMessageProvider msgProvider = (IMessageProvider)this.mObjectRegistry
      .getInstanceOfType(IMessageProvider.class);
    String langString = this.ServiceContext.getSession().getString("lang", 
      "ZHS");
    this.localMsgProvider = msgProvider.getLocalizedMessageProvider(langString);
    CompositeMap parameter = this.ServiceContext.getParameter();
    this.fileName = parameter.getString("_file_name_", "excel");
    this.fileType = parameter.getString("_format");
  }

  public void setContext(CompositeMap context) {
    this.ServiceContext = ((SqlServiceContext)DynamicObject.cast(context, 
      SqlServiceContext.class));
    initialization();
    if ("xlsx".equals(this.fileType))
      this.excelBean = new Excel2007Bean();
    else if ("xls".equals(this.fileType)) {
      this.excelBean = new Excel2007Bean();
    }
    this.wb = this.excelBean.getNewWorkbook();
    setCellStyle();
    this.creationHelper = this.wb.getCreationHelper();
    this.sheet = this.wb.createSheet();
    this.sheetNum = 0;
    try {
      createExcelHeader(createHeaderConfig(), this.sheet, this.sheet.createRow(0), -1);
      this.sheet.createFreezePane(0, this.headLevel + 1);
    } catch (ServletException e) {
      this.mLogger.log(Level.SEVERE, e.getMessage());
      throw new RuntimeException(e);
    }
  }

  CompositeMap createHeaderConfig() throws ServletException {
    CompositeMap columnConfig = (CompositeMap)this.ServiceContext.getParameter()
      .getObject(
      "_column_config_/column");

    if (columnConfig == null) {
      throw new ServletException(
        "service-output tag and output attibute must be defined");
    }
    CompositeMap contextMap = this.ServiceContext.getObjectContext();
    CompositeMap datatype = (CompositeMap)contextMap
      .getObject("/_export_datatype");
    if (datatype != null) {
      Iterator it = datatype.getChildIterator();
      if (it != null) {
        while (it.hasNext()) {
          CompositeMap record = (CompositeMap)it.next();
          String name = record.getString("field");
          CompositeMap columnRecord = columnConfig.getChildByAttrib(
            "record", "name", name);
          columnRecord.put("datatype", record
            .getString("datatype"
            .toLowerCase()));
        }
      }
    }
    return new MergedHeader(columnConfig).conifg;
  }

  int createExcelHeader(CompositeMap columnConfigs, Sheet sheet, Row header, int col)
  {
    int rownum = header.getRowNum();
    Iterator iterator = columnConfigs.getChildIterator();
    if (iterator != null) {
      while (iterator.hasNext()) {
        col++;
        CompositeMap record = (CompositeMap)iterator.next();
        String title = promptParse(record.getString("prompt"));
        Map map = (Map)this.headMap.get(Integer.valueOf(rownum));
        if (map != null) {
          map.put(Integer.valueOf(col), title);
        } else {
          map = new TreeMap();
          map.put(Integer.valueOf(col), title);
          this.headMap.put(Integer.valueOf(rownum), map);
        }

        int level = record.getInt("_level", 0);
        if (this.headLevel == 0) {
          this.headLevel = level;
        }
        Iterator it = record.getChildIterator();
        if (it != null) {
          Long span = (Long)record.getObject("column/@_count");
          CellRangeAddress range = new CellRangeAddress(rownum, 
            rownum, col, col + span.intValue() - 1);
          sheet.addMergedRegion(range);
          while (it.hasNext()) {
            Row nextRow = sheet.getRow(rownum + 1);
            if (nextRow == null)
              nextRow = sheet.createRow(rownum + 1);
            CompositeMap object = (CompositeMap)it.next();
            col = createExcelHeader(object, sheet, nextRow, col - 1);
          }
        } else {
          this.columnMap.put(Integer.valueOf(col), record);
          if (level != 0) {
            CellRangeAddress range = new CellRangeAddress(rownum, 
              rownum + level, col, col);
            sheet.addMergedRegion(range);
          }
        }
      }
    }
    return col;
  }

  String promptParse(String key) {
    String promptString = this.localMsgProvider.getMessage(key);
    promptString = promptString == null ? key : promptString;
    return promptString;
  }

  public void begin(String root_name) {
    Iterator iterator = this.headMap.entrySet().iterator();

    while (iterator.hasNext()) {
      Map.Entry entry = (Map.Entry)iterator.next();
      Integer rowIndex = (Integer)entry.getKey();
      Row row = this.sheet.createRow(rowIndex.intValue());
      Map map = (Map)this.headMap.get(rowIndex);
      Iterator colIterator = map.entrySet().iterator();
      while (colIterator.hasNext()) {
        Map.Entry colEntry = (Map.Entry)colIterator.next();
        int col = Integer.valueOf(((Integer)colEntry.getKey()).intValue()).intValue();
        if (col + 1 > this.excelBean.getColLimit())
          break;
        Cell cell = row.createCell(col);
        cell.setCellValue(this.creationHelper.createRichTextString((String)colEntry.getValue()));
        cell.setCellStyle(this.headstyle);
      }
    }
    createBodyStyle();
  }

  void createBodyStyle() {
    Iterator iterator = this.columnMap.entrySet().iterator();

    while (iterator.hasNext()) {
      Map.Entry entry = (Map.Entry)iterator.next();
      int col = Integer.valueOf(((Integer)entry.getKey()).intValue()).intValue();
      if (col + 1 > this.excelBean.getColLimit())
        break;
      CompositeMap record = (CompositeMap)entry.getValue();
      CellStyle style = this.wb.createCellStyle();
      style.cloneStyleFrom(this.bodystyle);
      style.setAlignment(getExcelAlign(record.getString("align")));
      this.styleMap.put(Integer.valueOf(col), style);
      int width = record.getInt("width", 100);
      this.sheet.setColumnWidth(col, (short)(width * 42));
    }
  }

  public void newRow(String row_name) {
    this.rowMap = new HashMap();
    this.headLevel += 1;
    if (this.headLevel % 10000 == 0) {
      System.out.println("数据已导出" + this.headLevel / 10000 + "万行");
    }
    this.sheetNum = (this.headLevel / this.excelBean.getRowLimit());
    if (this.headLevel % this.excelBean.getRowLimit() == 0)
    {
      this.sheet = this.wb.createSheet("Sheet" + this.sheetNum);
      this.sheet.setSelected(true);
    }
  }

  public void loadField(String name, Object value)
  {
    this.rowMap.put(name, value);
  }

  public void endRow()
  {
    int SheetRowMum = this.headLevel - this.sheetNum * this.excelBean.getRowLimit();
    Row row = this.sheet.createRow(SheetRowMum);
    Iterator iterator = this.columnMap.entrySet().iterator();

    while (iterator.hasNext()) {
      Map.Entry entry = (Map.Entry)iterator.next();
      int col = Integer.valueOf(((Integer)entry.getKey()).intValue()).intValue();
      if (col + 1 > this.excelBean.getColLimit())
        break;
      createCell(row.createCell(col), (CompositeMap)entry.getValue());
    }
  }

  void createCell(Cell cell, CompositeMap record) {
    CellStyle style = (CellStyle)this.styleMap.get(Integer.valueOf(cell.getColumnIndex()));
    cell.setCellStyle(style);
    Object value = this.rowMap.get(record.getString("name"));
    if (value != null)
      if (record.getString("datatype") != null)
      {
        if ("String".equalsIgnoreCase(record
          .getString("datatype")))
          cell.setCellValue(this.creationHelper.createRichTextString(value
            .toString()));
        else {
          try {
            cell.setCellValue(Double.parseDouble(value
              .toString()));
          } catch (Exception e) {
            cell.setCellValue(this.creationHelper.createRichTextString(value
              .toString()));
          }
        }
      }
      else if ((value instanceof String))
        cell.setCellValue(this.creationHelper.createRichTextString(value
          .toString()));
      else if ((value instanceof Number)) {
        cell.setCellValue(Double.parseDouble(value
          .toString()));
      }
      else if (value != null)
        cell.setCellValue(this.creationHelper.createRichTextString(value
          .toString()));
  }

  public void end()
  {
    boolean flag = true;
    System.out.println("导出即将完成,共" + this.headLevel / 10000 + "万");
    ServiceInstance svc = ServiceInstance.getInstance(this.ServiceContext.getObjectContext());
    HttpServletResponse response = ((HttpServiceInstance)svc).getResponse();
    setResponseHeader(((HttpServiceInstance)svc).getRequest(), response);
    OutputStream out = null;
    try {
      this.ServiceContext.putBoolean("responseWrite", true);
      out = response.getOutputStream();
    }
    catch (Exception e) {
      flag = false;
      System.out.println("导出失败。。。");
      this.mLogger.log(Level.SEVERE, e.getMessage());
      throw new RuntimeException(e);
    } finally {
      if (out != null) {
        try
        {
          this.wb.write(out);
          out.close();
        }
        catch (Exception localException1)
        {
        }
      }
    }
    if (flag)
      System.out.println("导出完成...");
  }

  public void setRecordCount(long count)
  {
  }

  public Object getResult()
  {
    return null;
  }
  void setResponseHeader(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType(this.excelBean.getMimeType());
    response.setCharacterEncoding("UTF-8");
    response.setHeader("cache-control", "must-revalidate");
    response.setHeader("pragma", "public");
    try {
      String userAgent = request.getHeader("User-Agent");
      if (userAgent != null) {
        userAgent = userAgent.toLowerCase();
        if (userAgent.indexOf("msie") != -1)
          this.fileName = new String(this.fileName.getBytes("GBK"), "ISO-8859-1");
        else {
          this.fileName = new String(this.fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
      }
      response.setHeader("Content-Disposition", "attachment; filename=\"" + 
        this.fileName + this.excelBean.getFileExtension() + "\"");
    } catch (UnsupportedEncodingException e) {
      this.mLogger.log(Level.SEVERE, e.getMessage());
      throw new RuntimeException(e);
    }
  }

  void setCellStyle() { this.headstyle = this.wb.createCellStyle();
    Font headfont = this.wb.createFont();
    headfont.setFontName("宋体");
    headfont.setBoldweight((short)700);
    headfont.setFontHeightInPoints((short)12);
    this.headstyle.setFont(headfont);
    this.headstyle.setAlignment((short)2);
    this.headstyle.setVerticalAlignment((short)1);

    this.bodystyle = this.wb.createCellStyle();
    this.bodystyle.setVerticalAlignment((short)1);
    Font bodyfont = this.wb.createFont();
    bodyfont.setFontName("宋体");
    bodyfont.setFontHeightInPoints((short)12);
    this.bodystyle.setFont(bodyfont); }

  short getExcelAlign(String align)
  {
    short excelAlign = 0;
    if ((align == null) || ("left".equalsIgnoreCase(align)))
      excelAlign = 1;
    else if ("right".equalsIgnoreCase(align))
      excelAlign = 3;
    else if ("center".equalsIgnoreCase(align))
      excelAlign = 2;
    return excelAlign;
  }
}

你可能感兴趣的:(poi测试代码)