⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xlsview.java

📁 ecside jsp前途分页的标签 实现ajax 增删改查等
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * Copyright 2006-2007 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.ecside.view;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import jxl.Cell;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.CellFormat;
import jxl.format.Colour;
import jxl.write.Blank;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.NumberFormat;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ecside.common.log.LogHandler;
import org.ecside.core.ECSideContext;
import org.ecside.core.TableModel;
import org.ecside.core.bean.Column;
import org.ecside.core.context.ContextUtils;
import org.ecside.preferences.PreferencesConstants;
import org.ecside.table.calc.CalcResult;
import org.ecside.table.calc.CalcUtils;
import org.ecside.util.ECSideUtils;
import org.ecside.util.ExportViewUtils;
import org.ecside.util.ExtremeUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;

/**
 * @author Wei Zijun
 *
 */

/**
 * com.extremecomp.table.view.XlsView.java -
 *
 * @author paul horn
 */

public class XlsView implements View {
    private Log logger = LogFactory.getLog(XlsView.class);
    public static final int WIDTH_MULT = 240; // width per char
    public static final int MIN_CHARS = 8; // minimum char width
    public static final short DEFAULT_FONT_HEIGHT = 8;
    public static final double NON_NUMERIC = -.99999;
    public static final String DEFAULT_MONEY_FORMAT = "$###,###,##0.00";
    public static final String DEFAULT_PERCENT_FORMAT = "##0.0%";
    public static final String NBSP = " ";
    
    public static final int colWidth=15;

    private WritableWorkbook wb;
    private WritableSheet sheet;

    private int rownum;
    private short cellnum;

    private String moneyFormat;
    private String percentFormat;
    private OutputStream outputStream;
    private String encoding;

    public XlsView() {
    	encoding=ECSideContext.ENCODING;
    }

    public void beforeBody(TableModel model) {
        logger.debug("XlsView.init()");
        
		outputStream=ContextUtils.getResponseOutputStream(model.getContext());
		if (outputStream==null){
			outputStream=new ByteArrayOutputStream();
		}
        
        moneyFormat = model.getPreferences().getPreference(PreferencesConstants.TABLE_EXPORTABLE + "format.money");
        if (StringUtils.isEmpty(moneyFormat)) {
            moneyFormat = DEFAULT_MONEY_FORMAT;
        }
        percentFormat = model.getPreferences().getPreference(PreferencesConstants.TABLE_EXPORTABLE + "format.percent");
        if (StringUtils.isEmpty(percentFormat)) {
            percentFormat = DEFAULT_PERCENT_FORMAT;
        }

//        encoding = model.getExportHandler().getCurrentExport().getEncoding();

        
        try {
			wb = Workbook.createWorkbook(outputStream);
	        sheet = wb.createSheet("Export Workbook",0);
	        createHeader(model);
//	        int totalCol=model.getColumnHandler().getColumns().size();

	        rownum++;
	        
	        String extendRowBefore=(String)(model.getTable().getAttribute("ExtendRowBefore"));
	        rownum+=createRow(sheet, getRows(extendRowBefore,encoding),(CellFormat)WritableWorkbook.NORMAL_STYLE, rownum,0)-1;
	        
		} catch (Exception e) {
			LogHandler.errorLog(logger, e);
		}
  
      
    }
    
    
    public static TableRow[] getRows(String inputHtml,String encode) throws Exception {
    	if (StringUtils.isBlank(inputHtml)){
    		return null;
    	}
    	inputHtml=inputHtml.trim();
    	if (!inputHtml.startsWith("<table>")&&!inputHtml.startsWith("<TABLE>") ){
    		inputHtml="<table>"+inputHtml+"</table>";
    	}
        Parser parser = Parser.createParser(inputHtml, encode);
        NodeList nodes = parser.extractAllNodesThatMatch(new NodeFilter() {
            public boolean accept(Node node) {
                return node instanceof TagNode;
            }
        });
        TagNode node = (TagNode)nodes.elementAt(0);
        
        return ((TableTag)node).getRows();
    }
    
    public static int getColumnNum(TableRow row){
    	int totalCol=0;
    	
    	TableColumn[] columns=row.getColumns();
    	
    	for (int cn=0;cn<columns.length;cn++){
    		String colspan=columns[cn].getAttribute("colspan");
    		if (colspan!=null&&colspan.length()>0){
    			try{
    				totalCol+=Integer.parseInt(colspan);
    				continue;
    			}catch(Exception e){}
    		}
    		totalCol++;
    	}
    	
    	return totalCol;
    	
    }
    
    public static int createRow(WritableSheet sheet,TableRow[] tableRows,CellFormat cellFormat,int startRow,int startCol) throws RowsExceededException, WriteException{

    	if (tableRows==null||tableRows.length<1) { return 0; }
    	int totalCol=getColumnNum(tableRows[0]);
//     			CellFormat cellFormat=(CellFormat)WritableWorkbook.NORMAL_STYLE;
    			int colWidth=15;
    		
    		List mergeCells=new ArrayList();
        		for (int rowNo=startRow;rowNo<startRow+tableRows.length;rowNo++ ){
        			int idx=0;
        			for (int colNo=startCol;colNo<startCol+totalCol;colNo++){
        			Cell cell=sheet.getCell(colNo,rowNo);
        			if (cell instanceof Blank) {
						continue;
        			}
        			TableColumn tdBean=((TableRow)tableRows[rowNo-startRow]).getColumns()[idx];
        			String title=ECSideUtils.specialHTMLToShowTEXT(tdBean.toPlainTextString());
        			
    	            Label label=new Label(colNo,rowNo,title,cellFormat); 
    	            sheet.addCell(label);
    	            sheet.setColumnView(colNo, colWidth);
    	            idx++; 	            
        				int ce=Integer.parseInt(ECSideUtils.convertString(tdBean.getAttribute("colspan"),"1"))-1;
        				int re=Integer.parseInt(ECSideUtils.convertString(tdBean.getAttribute("rowspan"),"1"))-1;
        				
        				if (ce>=1 || re>=1){
        					ce=ce<0?0:ce;
        					re=re<0?0:re;
        					mergeCells.add(new int[]{colNo,rowNo,colNo+ce,rowNo+re});
        					if (ce<1 && re>=1){
        		        		for (int srowNo=1;srowNo<=re; srowNo++){
        		    	            sheet.addCell(new Blank(colNo,rowNo+srowNo));
        		    	            sheet.setColumnView(colNo, colWidth);
        		        		}
        		        		continue;
        					}else if (re<1 && ce>=1){
        						for (int scolNo=1;scolNo<=ce;scolNo++){
        		    	            sheet.addCell(new Blank(colNo+scolNo,rowNo));
        		    	            sheet.setColumnView(colNo+scolNo, colWidth);
        		        		}
        		        		colNo+=ce;
        		        		continue;
        					}else if (ce>=1 && re>=1){
	        		    		for (int scolNo=1;scolNo<=ce;scolNo++){
	        		        		for (int srowNo=1;srowNo<=re; srowNo++){
	        		        			sheet.addCell(new Blank(colNo+scolNo,rowNo+srowNo));
	        		    	            sheet.setColumnView(colNo+scolNo, colWidth);
	        		        		}
	        		    		}
	        		    		colNo+=ce;
	        		    		continue;
	        				}
        				}
        			}

        		}

        		for (int i=0;i<mergeCells.size();i++){
        			int[] mc=(int[])mergeCells.get(i);
        			sheet.mergeCells(mc[0],mc[1],mc[2],mc[3]);
        		}

    	return tableRows.length;
    }
    
   
    private void createHeader(TableModel model) throws RowsExceededException, WriteException {
        rownum = 0;
        cellnum = 0;
        int etr=0;
        //HSSFRow row = sheet.createRow(rownum);

        
        WritableCellFormat cellFormat=new WritableCellFormat();
        WritableFont arial10font = new WritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.BOLD); 
        cellFormat.setBackground(Colour.GRAY_25);
        cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN,Colour.GRAY_50);
        cellFormat.setFont(arial10font);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -