JAVA導出EXCEL實現

##JAVA導出EXCEL實現的多種方式
java導出Excel的方法有多種,最爲常用的方式就是使用第三方jar包,目前POI和JXL是最常用的二方包了,也推薦使用這兩種。
###POI實現
POI這裏不詳細解釋,可參考徐老師發的博客:http://blog.csdn.net/evangel_z/article/details/7332535,他利用開源組件POI3.0.2動態導出EXCEL文檔的通用處理類ExportExcel,詳細使用方法下載最新代碼看看就可以裏,徐老師寫的很明瞭!總之思路就是用Servlet接受post、get請求,獲取文件導出路徑,然後將測試數據封裝好調用通用處理類導出Excel,然後再下載剛導出的Excel,會自動在瀏覽器彈出選擇保存路徑的彈出框,這樣就達到裏大家常見的文件導出下載的功能!當然,真正的項目裏不可能把文件導出到本地,肯定是先吧文件導出到服務器上,再去服務器下載,對於用戶來說就感覺好像直接就導出了!
這種實現邏輯也可以修改,就是把通用處理類ExportExcel從void改爲返回read好數據的InputStream,而不要直接就去write,然後調用下載的方法downLoad使用HttpServletResponse.getOutputStream()所得到的輸出流來write數據,然後調用flush()時就會在頁面彈出選擇路徑的彈出框,選擇好後數據就真正從緩存輸出到了Excel中,這樣就省去裏中間先要導出一次的步驟了。
###JXL實現
我這裏講一下JXL,其實和POI差不多,就是調用的組件不同,引入的jar包不同了,整個Excel導出下載的邏輯還是一樣的。好了,直接上代碼,都是通用代碼,以後都能用的上。
先是幾個mode類封裝了在處理過程中會用到的模型。
ExcelColMode 主要封裝的是Map中的key或者dto中實現get方法的字段名,其實就是表格的標題的屬性名。

public class ExcelColMode {

	/**
	 * Map中的key或者dto中實現get方法的字段名
	 */
	private String name;

	/** 列寬 */
	private Integer width;

	/**
	 * 字體格式,可以設置字體大小,字體顏色,字體加粗
	 */
	private ExcelFontFormat fontFormat;

	/**
	 * 內容格式化
	 */
	private ExcelColModelFormatterInter contentFormatter;

	public ExcelColMode(String name) {
		this.name = name;
	}

	public ExcelColMode(String name, Integer width) {
		this.name = name;
		this.width = width;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public ExcelFontFormat getFontFormat() {
		return fontFormat;
	}

	public void setFontFormat(ExcelFontFormat fontFormat) {
		this.fontFormat = fontFormat;
	}

	public ExcelColModelFormatterInter getContentFormatter() {
		return contentFormatter;
	}

	public void setContentFormatter(ExcelColModelFormatterInter contentFormatter) {
		this.contentFormatter = contentFormatter
	}

	public Integer getWidth() {
		return width;
	}

	public void setWidth(Integer width) {
		this.width = width;
	}

}

ExcelHeadCell 主要封裝的是標題名

public class ExcelHeadCell implements Comparable<ExcelHeadCell> {

	/**
	 * 列合併
	 */
	private int colSpan;

	/**
	 * 展現字符內容
	 */
	private String content;

	/**
	 * 父列的序列號
	 */
	private int fatherIndex;

	/**
	 * 字體格式等
	 */
	private ExcelFontFormat fontFormat;

	private Integer height;

	/**
	 * 最基礎的單元格,沒有行合併和列合併
	 * 
	 * @param content
	 */
	public ExcelHeadCell(String content) {
		this.colSpan = 1;
		this.content = content;
	}

	public ExcelHeadCell(String content, Integer height) {
		this.colSpan = 1;
		this.content = content;
		this.height = height;
	}

	public ExcelHeadCell(String content, int fatherIndex, ExcelFontFormat fontFormat) {
		this.colSpan = 1;
		this.content = content;
		this.fatherIndex = fatherIndex;
		this.fontFormat = fontFormat;
	}

	public int getColSpan() {
		return colSpan;
	}

	public void setColSpan(int colSpan) {
		this.colSpan = colSpan;
	}

	public String getContent() {
        return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public ExcelFontFormat getFontFormat() {
		return fontFormat;
	}

	public void setFontFormat(ExcelFontFormat fontFormat) {
		this.fontFormat = fontFormat;
	}

	public int getFatherIndex() {
		return fatherIndex;
	}

	public void setFatherIndex(int fatherIndex) {
		this.fatherIndex = fatherIndex;
	}

	public Integer getHeight() {
		return height;
	}

	public void setHeight(Integer height) {
		this.height = height;
	}

	public int compareTo(ExcelHeadCell o) {
		int i = -1;
		if (o == null) {
			i = 1;
		} else {
			i = o.fatherIndex > this.fatherIndex ? -1 : 1;
			if (o.fatherIndex == this.fatherIndex) {
				i = 0;
			}
		}
		return i;
	}
}

ExcelExportRule 主要封裝的是之前的ExcelColMode和ExcelHeadCell以及sheet頁名稱sheetName

public class ExcelExportRule {

	/**
	 * 封裝如何從數據集取數據,數據顯示格式,日期格式和數字格式在這裏設置
	 */
	private List<ExcelColMode> colModes;

	/**
	 * 封裝EXCEL頭部內容及內容顯示格式
	 */
	private List<List<ExcelHeadCell>> headCols;

	/**
	 * 數據背景顏色區分,0:不區分,1:按行奇偶區分,奇數行白色,偶數行灰色,2:按列奇偶區分 奇數列白色,偶數列灰色, <br/>
	 * <b>注意:此參數爲0時,單元格設置的背景色才起作用</b>
	 */
	private int distinguishable = 0;

	/**
	 * EXCEL的sheet頁名稱
	 */
	private String sheetName;

	/**
	 * 是否樹形結構,1:是,0:否
	 */
	private String hierarchical = "0";

	/**
	 * id字段名,當hierarchical="1"時候才起作用
	 */
	private String idName;

	/**
	 * 父id字段名,當hierarchical="1"時候才起作用
	 */
	private String pidName;

	public List<ExcelColMode> getColModes() {
		return colModes;
	}

	public void setColModes(List<ExcelColMode> colModes) {
		this.colModes = colModes;
	}

	public List<List<ExcelHeadCell>> getHeadCols() {
		return headCols;
	}

	public void setHeadCols(List<List<ExcelHeadCell>> headCols) {
		this.headCols = headCols;
	}

	public int getDistinguishable() {
		return distinguishable;
	}

	public void setDistinguishable(int distinguishable) {
		this.distinguishable = distinguishable;
	}

	public String getSheetName() {
		return sheetName;
	}

	public void setSheetName(String sheetName) {
		this.sheetName = sheetName;
	}

	public String getHierarchical() {
		return hierarchical;
	}

	public void setHierarchical(String hierarchical) {
		this.hierarchical = hierarchical;
	}

	public String getIdName() {
		return idName;
	}

	public void setIdName(String idName) {
		this.idName = idName;
	}

	public String getPidName() {
		return pidName;
	}

	public void setPidName(String pidName) {
		this.pidName = pidName;
	}

	public void addExcelColMode(ExcelColMode excelColMode) {
		if (colModes == null)
			colModes = new ArrayList<ExcelColMode>();
		colModes.add(excelColMode);
	}

	public void addExcelHeadCellList(List<ExcelHeadCell> list) {
		if (headCols == null)
			headCols = new ArrayList<List<ExcelHeadCell>>();
		headCols.add(list);
	}

}

ExcelFontFormat 封裝的是表格的一些樣式,如果對此沒什麼要求可以忽略

public class ExcelFontFormat {

	private int font = 0; // 字體 0:宋體,1:楷體,2:黑體,3:仿宋體,4:隸書
	private Colour color = Colour.BLACK; // 字體顏色
	private boolean bold = false; // 是否加粗
	private int flow = 0; // 文字浮動方向,0:靠左(默認),1:居中,2:靠右,
	private int fontSize = 0; // 文字大小,0:正常,-2,-1,0,1,2,3,4依次加大,最大到4
	private Colour backgroundColor = Colour.WHITE; // 單元格填充色
	private boolean italic;// 是否斜體
	private int verticalAlign = 1; // 文字上下對齊 0:上 1:中 2:下

	public int getFont() {
		return font;
	}

	public void setFont(int font) {
		this.font = font;
	}

	public Colour getColor() {
		return color;
	}

	public void setColor(Colour color) {
		this.color = color;
	}

	public Colour getBackgroundColor() {
		return backgroundColor;
	}

	public void setBackgroundColor(Colour backgroundColor) {
		this.backgroundColor = backgroundColor;
	}

	public boolean isBold() {
		return bold;
	}

	public void setBold(boolean bold) {
		this.bold = bold;
	}

	public int getFontSize() {
		return fontSize;
	}

	public void setFontSize(int fontSize) {
		this.fontSize = fontSize;
	}

	public int getFlow() {
		return flow;
	}

	public void setFlow(int flow) {
		this.flow = flow;
	}

	public Alignment convertFlow() {
		return convertFlow(flow);
	}
	
	public static Alignment convertFlow(int flow) {
		Alignment al = null;
		switch (flow) {
		case 0:
			al = Alignment.LEFT;
			break;
		case 1:
			al = Alignment.CENTRE;
			break;
		case 2:
			al = Alignment.RIGHT;
			break;
		default:
			al = Alignment.LEFT;
		}
		return al;
	}

	public FontName convertFontName() {
		return convertFontName(font);
	}
	
    public static FontName convertFontName(int font) {
		FontName fn = null;
		switch (font) {
		case 0:
			fn = WritableFont.createFont("SimSun");
			break;
		case 1:
			fn = WritableFont.createFont("KaiTi");
			break;
		case 2:
			fn = WritableFont.createFont("SimHei");
			break;
		case 3:
			fn = WritableFont.createFont("FangSong");
			break;
		case 4:
			fn = WritableFont.createFont("LiSu");
			break;
		default:
			fn = WritableFont.createFont("STSong");
		}
		return fn;
	}
	
	public int convertFontSize() {
		return convertFontSize(fontSize);
	}

	public static int convertFontSize(int fontSize) {
		return 12 + fontSize * 2;
	}

	@Override
	public boolean equals(Object obj) {
		boolean eq = false;
		if (this == obj) {
			eq = true;
		} else if (obj != null && obj instanceof ExcelFontFormat) {
			ExcelFontFormat e = (ExcelFontFormat) obj;
			if (e.bold == this.bold && e.backgroundColor == this.backgroundColor && e.color == this.color
					&& e.flow == this.flow && e.font == this.font && e.fontSize == this.fontSize
					&& e.italic == this.italic) {
				eq = true;
			}
		}
		return eq;
	}
	
	public boolean isItalic() {
		return italic;
	}

	public void setItalic(boolean italic) {
		this.italic = italic;
	}

	public int getVerticalAlign() {
		return verticalAlign;
	}

	public void setVerticalAlign(int verticalAlign) {
		this.verticalAlign = verticalAlign;
	}

}
	

4個mode類以及有了,我介紹的很簡單,每個封裝類其實還封裝了一些其他的,但因爲我的例子就只用到了這些就不多講了。下面是Excel處理類ExcelHelper,代碼比較多,其實大家不用管太多,粘貼過來用就行了,只要知道怎麼用他(包括輸入給些什麼,輸出的ByteArrayInputStream怎麼用)就行。

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableFont.FontName;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.JxlWriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.newsee.dto.common.ExcelColMode;
import com.newsee.dto.common.ExcelExportRule;
import com.newsee.dto.common.ExcelFontFormat;
import com.newsee.dto.common.ExcelHeadCell;

public class ExcelHelper {
    private static Log log = LogFactory.getLog(ExcelHelper.class);

	/**
	 * 實際需要展現的數據,支持DTO和Map
	 */
	private List<Object> rowDatas;

	private Set<Object> writed;

	/**
	 * 取數據及數據展現相關
	 */
	private List<ExcelColMode> colModes;

	/**
	 * 行頭(橫向排列),如果有父行頭則按父行頭的順序,沒有父行頭的按List順序排列
	 */
	private List<List<ExcelHeadCell>> headCols;

	/**
	 * 數據背景顏色區分,0:不區分,1:按行奇偶區分,2:按列奇偶區分
	 */
	private int distinguishable;

	/**
	 * 緩存展現內容的sheet頁
	 */
	private WritableSheet sheet;

	/**
	 * 緩存單元格格式
	 */
	private Map<ExcelFontFormat, WritableCellFormat> mappedFormat;

	/**
	 * id字段名稱,用於樹形結構
	 */
	private String idName;

	/**
	 * 父id字段名稱,用於樹形結構
	 */
	private String pidName;

	private static String ONE_BLANK = " ";

	private int curDataRowIndex;
	private int curExcelRowIndex;
	
	public InputStream writeExcel(List<Object> rowDatas, ExcelExportRule rule) throws IOException, WriteException,
			SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException,
			InvocationTargetException {
		if (rule != null) {
			this.rowDatas = rowDatas;
			this.colModes = rule.getColModes();
			this.headCols = rule.getHeadCols();
			this.distinguishable = rule.getDistinguishable();
			if (validate()) {
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
				String sheetName = rule.getSheetName();
				if (StringUtil.isBlank(sheetName)) {
					sheetName = "sheet0";
				}
				sheet = workbook.createSheet(sheetName, 0);
				// 設置列寬
				for (int i = 0; i < colModes.size(); i++) {
					ExcelColMode colMode = colModes.get(i);
					if (colMode.getWidth() != null)
						sheet.setColumnView(i, colMode.getWidth());
				}
				writeHeads();
				// 樹形結構
				if ("1".equals(rule.getHierarchical())) {
					this.idName = rule.getIdName();
					this.pidName = rule.getPidName();
					writeTreeBody();
				}
				// 非樹形結構
				else {
					writeBody();
				}
				workbook.write();
				workbook.close();
				return new ByteArrayInputStream(outputStream.toByteArray());
			}
		} else {
			log.error("ExcelExportRule爲空,無法導出excel");
		}
		return null;
	}
	
	private boolean validate() {
		if (colModes == null || colModes.size() == 0) {
			log.error("讀取數據的規則ExcelExportRule.colModes爲空");
			return false;
		}
		return true;
	}
	
	private void writeHeads() throws JxlWriteException, WriteException {
		curExcelRowIndex = 0;
		if (headCols != null && !headCols.isEmpty()) {
			int s = headCols.size();
			if (s > 1) {
				caculaterHeadColSpans();
			}
			for (int i = 0; i < s; i++) {
				int tempColIndex = 0;
				List<ExcelHeadCell> headRowCols = headCols.get(i);
				for (int j = 0; j < headRowCols.size(); j++) {
					ExcelHeadCell headCol = headRowCols.get(j);
					writeHeadCell(headCol, tempColIndex);
					tempColIndex += headCol.getColSpan();
				}
				curExcelRowIndex++;
			}
		}
	}

	// 計算標題需要列數
	private void caculaterHeadColSpans() {
	    int s = headCols.size();
		for (int i = s - 1; i > 0; i--) {
			List<ExcelHeadCell> subCols = headCols.get(i);
			Collections.sort(subCols);
			List<ExcelHeadCell> supCols = headCols.get(i - 1);
			int[] fatherColSpans = new int[supCols.size()];
			for (ExcelHeadCell subCol : subCols) {
				int fi = subCol.getFatherIndex();
				fatherColSpans[fi] += subCol.getColSpan();
			}
			for (int j = 0; j < supCols.size(); j++) {
				ExcelHeadCell supCol = supCols.get(j);
				if (fatherColSpans[j] > 0) {
					supCol.setColSpan(fatherColSpans[j]);
				}
			}
		}
	}

	private void writeHeadCell(ExcelHeadCell headCol, int colIndex) throws JxlWriteException, WriteException {
		ExcelFontFormat eff = headCol.getFontFormat();
		String content = headCol.getContent();
		int colspan = headCol.getColSpan();
		if (headCol.getHeight() != null)
			sheet.setRowView(curExcelRowIndex, headCol.getHeight(), false);
		writeCell(content, eff, colIndex, colspan);
	}

	private void writeCell(String content, ExcelFontFormat eff, int colIndex, int colspan) throws JxlWriteException,
			WriteException {
		if (eff != null) {
		WritableCellFormat wcf = getCellFormat(eff);
			sheet.addCell(new Label(colIndex, curExcelRowIndex, content, wcf));
		} else {
			sheet.addCell(new Label(colIndex, curExcelRowIndex, content));
		}
		if (colspan > 1) {
			sheet.mergeCells(colIndex, curExcelRowIndex, colIndex + colspan - 1, curExcelRowIndex);
		}
	}

	/**
	 * 從緩存中取格式化的字體,沒有則新建並緩存,生成EXCELL完成後需要清除緩存的字體
	 * 
	 * @param eff
	 * @return
	 * @throws WriteException
	 */
	private WritableCellFormat getCellFormat(ExcelFontFormat eff) throws WriteException {
		WritableCellFormat wcf = null;
		if (mappedFormat == null) {
			mappedFormat = new HashMap<ExcelFontFormat, WritableCellFormat>();
		} else {
			wcf = mappedFormat.get(eff);
		}
		if (wcf == null) {
			FontName fn = eff.convertFontName();
			WritableFont wf = new WritableFont(fn, eff.convertFontSize(), eff.isBold() ? WritableFont.BOLD
					: WritableFont.NO_BOLD, eff.isItalic(), UnderlineStyle.NO_UNDERLINE, eff.getColor());
			wcf = new WritableCellFormat(wf);
			wcf.setBackground(eff.getBackgroundColor());
			wcf.setAlignment(eff.convertFlow());
			wcf.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN, jxl.format.Colour.BLACK);
			if (eff.getVerticalAlign() == 0)
				wcf.setVerticalAlignment(VerticalAlignment.TOP);
			else if (eff.getVerticalAlign() == 1)
				wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
			else if (eff.getVerticalAlign() == 2)
				wcf.setVerticalAlignment(VerticalAlignment.BOTTOM);
			mappedFormat.put(eff, wcf);
		}
		return wcf;
	}

	private void writeTreeBody() throws RowsExceededException, WriteException, SecurityException,
			IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		if (rowDatas != null && rowDatas.size() > 0) {
			curDataRowIndex = 1;
			Object fo = rowDatas.get(0);
			boolean isMap = fo instanceof Map;
			if (isMap) {
				writeTreeDatas4Map();
			} else {
				writeTreeDatas4Dto();
			}
		}
	}

	private void writeTreeDatas4Map() throws JxlWriteException, WriteException {
		if (writed == null) {
		writed = new HashSet<Object>();
		}
		for (Object data : rowDatas) {
			if (!writed.contains(data)) {
				Map m = (Map) data;
				Object pid = m.get(pidName);
				if (pid == null) {
					writeRow4Map(data);
					curDataRowIndex++;
					curExcelRowIndex++;
					writed.add(data);
					writeSubDatas4Map(m, 1);
				} else {
					if (pid instanceof String) {
						String ps = (String) pid;
						if (StringUtil.isBlank(ps) || (Integer.valueOf(ps) <= 0)) {
							writeRow4Map(data);
							curDataRowIndex++;
							curExcelRowIndex++;
							writed.add(data);
							writeSubDatas4Map(m, 1);
						}
					} else if (pid instanceof Integer) {
						Integer pi = (Integer) pid;
						if (pi <= 0) {
							writeRow4Map(data);
							curDataRowIndex++;
							curExcelRowIndex++;
							writed.add(data);
							writeSubDatas4Map(m, 1);
						}
					} else if (pid instanceof Long) {
						Long pl = (Long) pid;
						if (pl.compareTo(0L) <= 0) {
							writeRow4Map(data);
							curDataRowIndex++;
							curExcelRowIndex++;
							writed.add(data);
							writeSubDatas4Map(m, 1);
						}
					} else if (pid instanceof BigDecimal) {
						if (((BigDecimal) pid).compareTo(BigDecimal.ZERO) <= 0) {
							writeRow4Map(data);
							curDataRowIndex++;
							curExcelRowIndex++;
							writed.add(data);
							writeSubDatas4Map(m, 1);
						}
					}
				}
			}
		}
	}

	private void writeSubDatas4Map(Map father, int deep) throws RowsExceededException, WriteException {
		for (Object data : rowDatas) {
			if (!writed.contains(data)) {
		        Map m = (Map) data;
				Object pid = m.get(pidName);
				Object fid = father.get(idName);
				if (pid != null) {
					if (pid instanceof Long) {
						Long pl = (Long) pid;
						Long fl = null;
						try {
							fl = (Long) fid;
						} catch (Exception e) {
							if (fid instanceof BigDecimal) {
								fl = ((BigDecimal) fid).longValue();
							}
						}
						if (pl.equals(fl)) {
							writeSubRow4Map(m, deep);
							curDataRowIndex++;
							curExcelRowIndex++;
							int subDeep = deep + 1;
							writed.add(data);
							writeSubDatas4Map(m, subDeep);
						}
					} else if (pid instanceof String) {
						String ps = (String) pid;
						String fs = null;
						try {
							fs = (String) fid;
						} catch (Exception e) {
							if (fid instanceof BigDecimal) {
								fs = ((BigDecimal) fid).toString();
							}
						}
						if (ps.equals(fs)) {
							writeSubRow4Map(m, deep);
							curDataRowIndex++;
							curExcelRowIndex++;
							int subDeep = deep + 1;
							writed.add(data);
							writeSubDatas4Map(m, subDeep);
						}
					} else if (pid instanceof Integer) {
						Integer pi = (Integer) pid;
						Integer fi = null;
						try {
							fi = (Integer) fid;
						} catch (Exception e) {
							if (fid instanceof BigDecimal) {
								fi = ((BigDecimal) fid).intValue();
							}
						}
						if (pi.equals(fi)) {
							writeSubRow4Map(m, deep);
							curDataRowIndex++;
							curExcelRowIndex++;
							int subDeep = deep + 1;
							writed.add(data);
							writeSubDatas4Map(m, subDeep);
						}
					}
				}
			}
		}
	}

	private void writeSubRow4Map(Map subMap, int deep) throws RowsExceededException, WriteException {
	int tempColIndex = 0;
		for (ExcelColMode mode : colModes) {
			Object o = subMap.get(mode.getName());
			String content = null;
			if (o == null)
				content = "";
			else {
				if (mode.getContentFormatter() != null)
					content = mode.getContentFormatter().format(o);
				else
					content = o.toString();
			}
			if (tempColIndex == 0) {
				int blankCount = 6 * deep;
				for (int i = 0; i < blankCount; i++) {
					content = ONE_BLANK + content;
				}
			}
			writeContent(content, mode, tempColIndex);
			tempColIndex++;
		}
	}

	private void writeTreeDatas4Dto() throws SecurityException, IllegalArgumentException, NoSuchMethodException,
			IllegalAccessException, InvocationTargetException, JxlWriteException, WriteException {
		if (writed == null) {
			writed = new HashSet<Object>();
		}
		for (Object data : rowDatas) {
		if (!writed.contains(data)) {
				Object pid = getValue(data, pidName);
				if (pid == null) {
					writeRow4Dto(data);
					curDataRowIndex++;
					curExcelRowIndex++;
					writed.add(data);
					writeSubDatas4Dto(data, 1);
				} else {
					if (pid instanceof String) {
						String ps = (String) pid;
						if (StringUtil.isBlank(ps) || (Integer.valueOf(ps)) <= 0) {
							writeRow4Dto(data);
							curDataRowIndex++;
							curExcelRowIndex++;
							writed.add(data);
							writeSubDatas4Dto(data, 1);
						}
					} else if (pid instanceof Integer) {
						Integer pi = (Integer) pid;
						if (pi <= 0) {
							writeRow4Dto(data);
							curDataRowIndex++;
							curExcelRowIndex++;
							writed.add(data);
							writeSubDatas4Dto(data, 1);
						}
					} else if (pid instanceof Long) {
						Long pl = (Long) pid;
						if (pl.compareTo(0L) <= 0) {
							writeRow4Dto(data);
							curDataRowIndex++;
							curExcelRowIndex++;
							writed.add(data);
							writeSubDatas4Dto(data, 1);
						}
					}
				}
			}
		}
	}

	private void writeSubDatas4Dto(Object father, int deep) throws SecurityException, IllegalArgumentException,
			NoSuchMethodException, IllegalAccessException, InvocationTargetException, RowsExceededException,
			WriteException {
		for (Object data : rowDatas) {
			if (!writed.contains(data)) {
			Object pid = getValue(data, pidName);
				Object fid = getValue(father, idName);
				if (pid != null) {
					if (pid instanceof Long) {
						Long pl = (Long) pid;
						Long fl = (Long) fid;
						if (pl.equals(fl)) {
							writeSubRow4Dto(data, deep);
							curDataRowIndex++;
							curExcelRowIndex++;
							int subDeep = deep + 1;
							writed.add(data);
							writeSubDatas4Dto(data, subDeep);
						}
					} else if (pid instanceof String) {
						String ps = (String) pid;
						String fs = (String) fid;
						if (ps.equals(fs)) {
							writeSubRow4Dto(data, deep);
							curDataRowIndex++;
							curExcelRowIndex++;
							int subDeep = deep + 1;
							writed.add(data);
							writeSubDatas4Dto(data, subDeep);
						}
					} else if (pid instanceof Integer) {
						Integer pi = (Integer) pid;
						Integer fi = (Integer) fid;
						if (pi.equals(fi)) {
							writeSubRow4Dto(data, deep);
							curDataRowIndex++;
							curExcelRowIndex++;
							int subDeep = deep + 1;
							writed.add(data);
							writeSubDatas4Dto(data, subDeep);
						}
					}
				}
			}
		}
	}

	private void writeSubRow4Dto(Object subData, int deep) throws SecurityException, IllegalArgumentException,
			NoSuchMethodException, IllegalAccessException, InvocationTargetException, RowsExceededException,WriteException {
		int tempColIndex = 0;
		for (ExcelColMode mode : colModes) {
			String field = mode.getName();
			Object o = getValue(subData, field);
			String content = null;
			if (o == null)
				content = "";
			else {
				if (mode.getContentFormatter() != null)
					content = mode.getContentFormatter().format(o);
				else
					content = o.toString();
			}
			if (tempColIndex == 0) {
				int blankCount = 6 * deep;
				for (int i = 0; i < blankCount; i++) {
					content = ONE_BLANK + content;
				}
			}
			writeContent(content, mode, tempColIndex);
		}
	}

	private void writeBody() throws RowsExceededException, WriteException, SecurityException, IllegalArgumentException,
			NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		if (rowDatas != null && rowDatas.size() > 0) {
			curDataRowIndex = 1;
			Object fo = rowDatas.get(0);
			if (fo instanceof Map) {
				writeDatas4Map();
			} else {
				writeDatas4Dto();
			}
		}
	}

	private void writeDatas4Map() throws JxlWriteException, WriteException {
		for (Object data : rowDatas) {
			writeRow4Map(data);
			curDataRowIndex++;
			curExcelRowIndex++;
			}
	}

	private void writeDatas4Dto() throws JxlWriteException, WriteException, SecurityException,
			IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		for (Object data : rowDatas) {
			writeRow4Dto(data);
			curDataRowIndex++;
			curExcelRowIndex++;
		}
	}

	private void writeRow4Map(Object data) throws JxlWriteException, WriteException {
		Map m = (Map) data;
		int tempColIndex = 0;
		for (ExcelColMode mode : colModes) {
			Object o = m.get(mode.getName());
			String content = null;
			if (o == null)
				content = "";
			else {
				if (mode.getContentFormatter() != null)
					content = mode.getContentFormatter().format(o);
				else
					content = o.toString();
			}
			writeContent(content, mode, tempColIndex);
			tempColIndex++;
		}
	}

	private void writeContent(String content, ExcelColMode mode, int colIndex) throws RowsExceededException,
			WriteException {
		ExcelFontFormat eff = mode.getFontFormat();
		if (distinguishable == 1) {
			if (eff == null) {
				eff = new ExcelFontFormat();
			}
			if (curDataRowIndex % 2 == 1) {
				eff.setBackgroundColor(Colour.WHITE);
			} else {
				eff.setBackgroundColor(Colour.GRAY_25);
			}
		} else if (distinguishable == 2) {
			if (eff == null) {
				eff = new ExcelFontFormat();
			}
			if (colIndex % 2 == 1) {
				eff.setBackgroundColor(Colour.WHITE);
			} else {
				eff.setBackgroundColor(Colour.GRAY_25);
			}
		}
		writeCell(content, eff, colIndex, 1);
	}

	private void writeRow4Dto(Object data) throws JxlWriteException, WriteException, SecurityException,
			IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		int tempColIndex = 0;
		for (ExcelColMode mode : colModes) {
			String field = mode.getName();
			Object o = getValue(data, field);
			String content = null;
			if (o == null)
				content = "";
			else {
				if (mode.getContentFormatter() != null)
					content = mode.getContentFormatter().format(o);
				else
					content = o.toString();
			}
			writeContent(content, mode, tempColIndex);
			tempColIndex++;
		}
	}

	private Object getValue(Object data, String feild) throws SecurityException, NoSuchMethodException,
			IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		if (feild.contains(".")) {
			String fileds[] = feild.split("\\.");
			Object value = null;
			String methodName = "get" + fileds[0].substring(0, 1).toUpperCase() + fileds[0].substring(1);
			try {
				Method getMethod = data.getClass().getMethod(methodName);
				value = getMethod.invoke(data);
			} catch (NoSuchMethodException e) {
				// e.printStackTrace();
				try {
					methodName = "get" + feild.substring(0, 1).toLowerCase() + feild.substring(1);
					Method getMethod = data.getClass().getMethod(methodName);
					value = getMethod.invoke(data);
				} catch (Exception e2) {
					e.printStackTrace();
				}
			}

			Object value2 = null;
			String methodName2 = "get" + fileds[1].substring(0, 1).toUpperCase() + fileds[1].substring(1);
			try {
				Method getMethod = value.getClass().getMethod(methodName2);
				value2 = getMethod.invoke(value);
			} catch (NoSuchMethodException e) {
				// e.printStackTrace();
				try {
					methodName = "get" + fileds[1].substring(0, 1).toLowerCase() + fileds[1].substring(1);
					Method getMethod = data.getClass().getMethod(methodName);
					value = getMethod.invoke(value);
				} catch (Exception e2) {
					e.printStackTrace();
				}
			}
			return value2;
		} else {
			Object value = null;
			String methodName = "get" + feild.substring(0, 1).toUpperCase() + feild.substring(1);
			try {
				Method getMethod = data.getClass().getMethod(methodName);
				value = getMethod.invoke(data);
			} catch (NoSuchMethodException e) {
				// e.printStackTrace();
				try {
					methodName = "get" + feild.substring(0, 1).toLowerCase() + feild.substring(1);
					Method getMethod = data.getClass().getMethod(methodName);
					value = getMethod.invoke(data);
				} catch (Exception e2) {
					e.printStackTrace();
				}
			}
			return value;
		}
	}

	/**
	 * 釋放資源
	 */
	public void clear() {
		if (writed != null) {
			writed = null;
		}
		if (rowDatas != null) {
			rowDatas = null;
		}
		if (colModes != null) {
			colModes = null;
		}
		if (headCols != null) {
			headCols = null;
		}
		if (sheet != null) {
			sheet = null;
		}
		if (mappedFormat != null) {
			mappedFormat = null;
		}
		if (idName != null) {
			idName = null;
		}
		if (pidName != null) {
			pidName = null;
		}
	}

	private static boolean isContainStyle(String style, String s1, String s2) {
		String styleArr[] = style.split(";");
		for (String s : styleArr) {
			if (s.contains(s1) && s.contains(s2))
				return true;
		}
		return false;
	}

	private static void writeSheetData(Integer startRow[], int level, Map<String, String> map, List<String> ridAry,
			List<Map<String, String>> allData, WritableSheet sheet) throws RowsExceededException, WriteException {
		String tab = "";
		for (int i = 0; i < level - 1; i++) {
			tab += "   ";
		}
		sheet.addCell(new Label(0, startRow[0], tab + map.get("index")));
		for (int i = 0; i < ridAry.size(); i++) {
			sheet.addCell(new Label(i + 1, startRow[0], map.get("R" + ridAry.get(i))));
		}
		startRow[0]++;
		List<Map<String, String>> children = getChildren(allData, map.get("id"));
		if (children != null && children.size() > 0) {
			for (Map<String, String> child : children) {
				writeSheetData(startRow, level + 1, child, ridAry, allData, sheet);
			}
		}
	}

	private static List<Map<String, String>> getFirstLeve(List<Map<String, String>> list) {
		List<Map<String, String>> firstLevel = new ArrayList<Map<String, String>>();
		if (list != null && list.size() > 0) {
			for (Map<String, String> map : list) {
				if (map.get("parentId") == null || map.get("parentId").length() == 0)
					firstLevel.add(map);
			}
		}
		return firstLevel;
	}

	private static List<Map<String, String>> getChildren(List<Map<String, String>> list, String id) {
		List<Map<String, String>> children = new ArrayList<Map<String, String>>();
		if (list != null && list.size() > 0) {
			for (Map<String, String> map : list) {
				if (map.get("parentId") != null && map.get("parentId").toString().equals(id))
					children.add(map);
			}
		}
		return children;
	}

	private static String getIndexData(String code, String rid, Map<String, List<HashMap<String, Object>>> tabDataMap) {
		if (code == null || code.length() == 0)
			return "";
		if (tabDataMap == null || tabDataMap.size() == 0)
			return "0";
		String codeArr[] = code.split("\\.");
		if (codeArr.length != 2)
			return "";
		List<HashMap<String, Object>> listMap = tabDataMap.get(codeArr[0]);
		if (listMap == null || listMap.size() == 0)
			return "0";
		else {
			for (int i = 0; i < listMap.size(); i++) {
				HashMap<String, Object> map = listMap.get(i);
				if (map.get("P_R_ID").toString().equals(rid)) {
					Object obj = map.get(codeArr[1]);
					if (obj != null)
						return obj.toString();
					else
						return "0";
					}
			}
			return "";
		}
	}

	private static String getUnit(String code, Map<String, String> tabUnitMap) {
		String result = "";
		if (code != null) {
			String codeArr[] = code.split("\\.");
			if (codeArr.length == 2) {
				if (tabUnitMap.get(codeArr[0]) != null)
					result = tabUnitMap.get(codeArr[0]);
			}
		}
		return result;
	}
}

接下來是測試類。

public class TestExcelUtil {
	@Test
	public void test() throws Exception {
		ExcelHelper excelHelper = new ExcelHelper();
		List<Object> rowDatas = new ArrayList<Object>();
		Map<String, String> map = new HashMap<String, String>();
		map.put("userName", "張三");
		map.put("sex", "男");
		rowDatas.add(map);

		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("userName", "李四");
		map1.put("sex", "男");
		rowDatas.add(map1);

		List<ExcelHeadCell> headCells = new ArrayList<ExcelHeadCell>();
		headCells.add(new ExcelHeadCell("姓名"));
		headCells.add(new ExcelHeadCell("性別"));
		List<List<ExcelHeadCell>> headCellsList = new ArrayList<List<ExcelHeadCell>>();
		headCellsList.add(headCells);
		ExcelExportRule rule = new ExcelExportRule();
		rule.setSheetName("測試");
		rule.setHeadCols(headCellsList);

		List<ExcelColMode> colModes = new ArrayList<ExcelColMode>();
		colModes.add(new ExcelColMode("userName"));
		colModes.add(new ExcelColMode("sex"));
		rule.setColModes(colModes);

		InputStream inputStream = excelHelper.writeExcel(rowDatas, rule);
		File file = new File("d:/test.xls");
		if (file.exists())
			file.delete();
		file.createNewFile();
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		byte b[] = new byte[512];
		int i = inputStream.read(b);
		while (i != -1) {
			fileOutputStream.write(b);
			i = inputStream.read(b);
		}
		fileOutputStream.flush();
		fileOutputStream.close();
		inputStream.close();
	}
}

通過看測試類應該就知道使用方法了吧,最後再給一個實際的從頁面到後臺的例子:從頁面發來的一個請求,包含了表格的標題、內容、sheet名、Excel名,然後實現生成並下載Excel(在頁面會彈出選擇保存路徑框)的過程。
首先是頁面:

<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
	<title>導出Excel</title>
	<script src="../../../ns-face-sys/common/lib/jquery-1.11.2.min.js"></script>
	<script src="../../../ns-face-sys/common/js/newsee.js"></script>
	<script src="../../../ns-face-sys/common/js/newsee.ui.js"></script>
</head>
<body>
<form id="formid"  name= "myform" method = "post"  action = "/ns-face-sys/rest/system/export/excel">
	<input id="headCells" name="headCells" value="" type="hidden"/>
	<input id="rowDatas" name="rowDatas" value="" type="hidden"/>
	<input id="sheetName" name="sheetName" value="人員信息" type="hidden"/>
	<input id="excelName" name="excelName" value="人員信息表" type="hidden"/>
	<table id="table">
		<tr>
			<td>序號</td>
			<td>姓名</td>
			<td>備註</td>
		</tr>
		<tr>
			<td>1</td>
			<td>yjc</td>
	        <td>欣lp</td>
		</tr>
		<tr>
			<td>2</td>
			<td>lsx</td>
			<td>誠lg</td>
		</tr>
		<tr>
			<td>3</td>
			<td>測試1</td>
			<td>備註1</td>
		</tr>
		<tr>
			<td>4</td>
			<td>測試2</td>
			<td>備註2</td>
		</tr>
	</table>
	<input id="export" type="button" value="導出Excel" onclick="exportExcel()"/>
</form>
<script type="text/javascript" src="export_excel.js"></script>
</body>
</html>

然後是js,裏面做了把表格數據整合成後臺需要的數據(每列數據用",“隔開,每行數據用”;"隔開,標題和內容分別放在隱藏的input裏傳給後臺解析),放到隱藏域裏,然後以提交表單的形式發送到後臺。
千萬注意:不要使用ajax請求,雖然也能發到後臺,但會導致瀏覽器收不到response,導致彈不出選擇保存路徑的彈出框了!!!

function exportExcel(){
	document.charset='utf-8';
	var head = getHead();
	var data = getData();
//	var path = getPath();
	$("#headCells").val(head);
	$("#rowDatas").val(data);
	$("#formid").submit();
	
//	var postData = [{
//        Request: {
//            Data: {
//            	headCells : head,
//    			rowDatas : data,
//    			sheetName : "人員信息",
//    			path : path,
//    			excelName : "人員信息表"
//            }
//        }
//    }]
//	$.ajax({
//            url: "/ns-face-sys/rest/system/export/excel",
//            type: "post",
//            dataType: 'json',
//            async: true,
//            data: { 
//            	request: newsee.base.JsonArrayToStringCfz(postData) 
//            }
//	});
function getHead(){
	var head = "";
	var uls = $("#table").find("tr");
	var lis =  $(uls[0]).children("td");
	for(var j=0;j<lis.length;j++){
		if(j == lis.length-1){
			head += $(lis[j]).text();
		}else{
			head += $(lis[j]).text() + ",";
		}
	}
	return head;
}

function getData(){
	var data = "";
	var uls = $("#table").find("tr");
	for(var i=1;i<uls.length;i++){
		var lis =  $(uls[i]).children("td");
		for(var j=0;j<lis.length;j++){
			if(j == lis.length-1 && i == uls.length-1){
				data += $(lis[j]).text();
			}else if(j == lis.length-1 && i != uls.length-1){
				data += $(lis[j]).text() + ";";
			}else{
				data += $(lis[j]).text() + ",";
			}
		}
	}
	return data;
}

function getPath(){
	return "D:";
}

然後時控制器層代碼,裏面爲了解決頁面過來的數據有中文亂碼,採用了笨方法,一個一個指定解碼方式

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import org.springframework.stereotype.Controller;

import com.newsee.face.common.ExportExcel;

@Path("system")
@Controller
public class SystemExcelFace {
	
	/**
	 * 導出excel入口
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@POST
	@Path("/export/excel")
	public void showImg(@FormParam("headCells") String headCells,
			@FormParam("rowDatas") String rowDatas,
			@FormParam("sheetName") String sheetName,
			@FormParam("excelName") String excelName,
			@Context HttpServletResponse response) throws Exception {
		headCells=new String(headCells.getBytes("iso-8859-1"),"UTF-8");
		rowDatas=new String(rowDatas.getBytes("iso-8859-1"),"UTF-8");
		sheetName=new String(sheetName.getBytes("iso-8859-1"),"UTF-8");
		excelName=new String(excelName.getBytes("iso-8859-1"),"UTF-8");
		new ExportExcel().exportExcel(rowDatas, headCells, sheetName, excelName,response);
	}

}

然後就是業務邏輯層了ExportExcel,這裏就調用了之前介紹的導出Excel處理類ExcelHelper。

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.newsee.dto.common.ExcelColMode;
import com.newsee.dto.common.ExcelExportRule;
import com.newsee.dto.common.ExcelHeadCell;
import com.newsee.util.ExcelHelper;
import com.newsee.util.StringUtil;

/**
 * 導出excel
 * 
 * @author yaojiacheng
 *
 */
public class ExportExcel {

	/**
	 * 導出excel
	 * 
	 * @param requestContent
	 * @return
	 */
	public void exportExcel(String rowData,String headCell,String sheetName,String excelName, HttpServletResponse response) throws Exception {
	if (StringUtil.isAnyBlank(rowData, headCell)) {
			return;
		}
		if(response == null){
			return;
		}

		ExcelHelper excelHelper = new ExcelHelper();

		List<ExcelHeadCell> headCells = new ArrayList<ExcelHeadCell>();
		String[] headCellsArray = headCell.split(",");
		for (String hc : headCellsArray) {
			headCells.add(new ExcelHeadCell(hc));
		}
		List<List<ExcelHeadCell>> headCellsList = new ArrayList<List<ExcelHeadCell>>();
		headCellsList.add(headCells);
		
		ExcelExportRule rule = new ExcelExportRule();
		if (StringUtil.isBlank(sheetName)) {
			rule.setSheetName("測試");
		} else {
			rule.setSheetName(sheetName);
		}
		rule.setHeadCols(headCellsList);

		List<ExcelColMode> colModes = new ArrayList<ExcelColMode>();
		for (int i = 0; i < headCellsArray.length; i++) {
			colModes.add(new ExcelColMode(i + ""));
		}
		rule.setColModes(colModes);
		
        List<Object> rowDatas = new ArrayList<Object>();
		String[] rowDataArrays = rowData.split(";");
		for (String rowDataArray : rowDataArrays) {
			Map<String, String> map = new HashMap<String, String>();
			String[] rowDataAs = rowDataArray.split(",");
			for (int i = 0; i < rowDataAs.length; i++) {
				map.put(i + "", rowDataAs[i]);
			}
			rowDatas.add(map);
		}

		InputStream fis = excelHelper.writeExcel(rowDatas, rule);
		byte b[] = new byte[512];
		// 清空response
		response.reset();
		// 設置response的Header
		response.addHeader("Content-Disposition", "attachment;filename=" + 
		URLEncoder.encode(excelName, "UTF-8")+ ".xls");
		response.addHeader("Content-Length", "" + fis.available());
		OutputStream toClient = new BufferedOutputStream(
				response.getOutputStream());
		response.setContentType("application/vnd.ms-excel;charset=gb2312");
		int i = fis.read(b);
		while (i != -1) {
			toClient.write(b);
			i = fis.read(b);
		}
		toClient.flush();
		toClient.close();
		fis.close();
	}

}

如上,使用response.getOutputStream()得到的輸出流來write數據後會先放在緩存中,到執行toClient.flush()就會在頁面彈出選擇保存路徑的選擇框,點擊保存後就下載成功了。這裏沒有Excel導出的過程,直接將經過Excel處理類得到的InputStream拿過來讀取,然後寫進OutputStream下載,通常這是最優的方式。
以上代碼沒有添加合併單元格的功能,需要合併單元格的同學們,可以自行修改代碼,合併調用的方法就是:WritableSheet.mergeCells(int m,int n,int p,int q); 作用是從(m,n)到(p,q)的單元格全部合併,比如:
//合併第一列第二行到第六列第二行的所有單元格
sheet.mergeCells(0,1,5,1); //注意了m和p指的是列,n和q指的是行
可以在workbook.write();workbook.close();之前調用即可!
還需要注意的是,合併的單元格顯示的內容是第一個單元格的內容,不是所有單元格的內容追加!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章