精华内容
下载资源
问答
  • java导出excel合并行跟列

    千次阅读 2014-05-07 15:36:54
    sheet.addMergedRegion(new CellRangeAddress(row + i, row + i, 2, 4));// 分公司数据单元格合并
    CellRangeAddress(从第几行开始, 到第几行结束,从第几列开始, 到第几列结束);单元格合并

    展开全文
  • JAVA导出EXCEL实现

    万次阅读 多人点赞 2019-07-31 18:39:28
    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();之前调用即可!
    还需要注意的是,合并的单元格显示的内容是第一个单元格的内容,不是所有单元格的内容追加!

    展开全文
  • Java导出Excel合并单元格

    千次阅读 2019-02-07 13:56:11
    Java导出Excel合并单元格
                   

    1、问题背景

         利用POI导出Excel表格,在导出的过程中涉及到双表头,即需要合并单元格


    2、实现源码

    /** *  * @Project:Report * @Title:MergeCell.java * @Package:com.you.excel * @Description: * @Author:YouHaiDong * @Date:2015年11月4日 下午2:36:46 * @Version: */package com.you.excel;import java.io.FileOutputStream;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFRichTextString;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.hssf.util.Region;/** * <p>合并单元格</p> * @ClassName:MergeCell * @Description: * @Author:YouHaiDong * @Date:2015年11月4日 下午2:36:46 *  */public class MergeCell /**  * 合并单元格  * @Title:MergeCell  * @Description:  * @param args  * @Date:2015年11月4日 下午2:36:46  * @return: void   * @throws Exception  */ @SuppressWarnings({ "resource", "deprecation" }) public static void main(String[] args) throws Exception  {  //创建workbook   HSSFWorkbook workbook = new HSSFWorkbook();   //创建sheet页     HSSFSheet sheet = workbook.createSheet("学生表");   //创建单元格  HSSFRow row = sheet.createRow(0);   HSSFCell c0 = row.createCell(0);   c0.setCellValue(new HSSFRichTextString("学号"));   HSSFCell c1 = row.createCell(1);   c1.setCellValue(new HSSFRichTextString("姓名"));   HSSFCell c2 = row.createCell(2);   c2.setCellValue(new HSSFRichTextString("性别"));   HSSFCell c3 = row.createCell(3);   c3.setCellValue(new HSSFRichTextString("年龄"));   HSSFCell c4 = row.createCell(4);   c4.setCellValue(new HSSFRichTextString("2015年分数"));   HSSFCell c5 = row.createCell(7);   c5.setCellValue(new HSSFRichTextString("2014年分数"));   HSSFRow row1 = sheet.createRow(1);   HSSFCell c6 = row1.createCell(4);   c6.setCellValue(new HSSFRichTextString("语文"));   HSSFCell c7 = row1.createCell(5);   c7.setCellValue(new HSSFRichTextString("数学"));   HSSFCell c8 = row1.createCell(6);   c8.setCellValue(new HSSFRichTextString("外语"));  HSSFCell c9 = row1.createCell(7);   c9.setCellValue(new HSSFRichTextString("语文"));   HSSFCell c10 = row1.createCell(8);   c10.setCellValue(new HSSFRichTextString("数学"));   HSSFCell c11 = row1.createCell(9);   c11.setCellValue(new HSSFRichTextString("外语"));    Region region1 = new Region(0, (short)0, 1, (short)0);   Region region2 = new Region(0, (short)1, 1, (short)1);   Region region3 = new Region(0, (short)2, 1, (short)2);   Region region4 = new Region(0, (short)3, 1, (short)3);   Region region5 = new Region(0, (short)4, 0, (short)6);   Region region6 = new Region(0, (short)7, 0, (short)9);   sheet.addMergedRegion(region1);   sheet.addMergedRegion(region2);   sheet.addMergedRegion(region3);   sheet.addMergedRegion(region4);   sheet.addMergedRegion(region5);   sheet.addMergedRegion(region6);     FileOutputStream stream = new FileOutputStream("d:/student.xls");   workbook.write(stream); }}

    3、实现结果


               

    再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

    展开全文
  • java导出Excel合并单元格

    万次阅读 多人点赞 2017-10-22 11:43:03
    网上java导出excel表格并合并单元格的资料不完全,我整理了一份,并亲测能用,附截图。 ①java导出excel用到POI所有jar包,大家可以直接到下面地址下载点击打开链接 ②模拟数据类 package org; public class ...

    网上java导出excel表格并合并单元格的资料不完全,我整理了一份,并亲测能用,附截图。

    ①java导出excel用到POI所有jar包,大家可以直接到下面地址下载点击打开链接

    ②模拟数据类

    package org;
    
    public class WorkSheetDetail {
        //工作内容
        private String workCtx;
        // 用工人总数	工日数 = gwnNum+tmnNum
        private Float totalHumanDays;
        //普工用工数 1-4小时为半天,4-8小时为一天;120每天
        private Integer gwnNum;
        //技工用工数 1-4小时为半天,4-8小时为一天;160每天
        private Integer tmnNum;
        // 单价(元)
        private Float unitPrice;
        // 金额(元) = gwnNum*120+tmnNum+160
        private Float unitAmount;
        // 备注
        private String notes; 
        
    	public WorkSheetDetail(String workCtx, Float totalHumanDays, Integer gwnNum, Integer tmnNum, Float unitPrice,
    			Float unitAmount, String notes) {
    		super();
    		this.workCtx = workCtx;
    		this.totalHumanDays = totalHumanDays;
    		this.gwnNum = gwnNum;
    		this.tmnNum = tmnNum;
    		this.unitPrice = unitPrice;
    		this.unitAmount = unitAmount;
    		this.notes = notes;
    	}
    	public String getWorkCtx() {
    		return workCtx;
    	}
    	public void setWorkCtx(String workCtx) {
    		this.workCtx = workCtx;
    	}
    	public Float getTotalHumanDays() {
    		return totalHumanDays;
    	}
    	public void setTotalHumanDays(Float totalHumanDays) {
    		this.totalHumanDays = totalHumanDays;
    	}
    	public Integer getGwnNum() {
    		return gwnNum;
    	}
    	public void setGwnNum(Integer gwnNum) {
    		this.gwnNum = gwnNum;
    	}
    	public Integer getTmnNum() {
    		return tmnNum;
    	}
    	public void setTmnNum(Integer tmnNum) {
    		this.tmnNum = tmnNum;
    	}
    	public Float getUnitPrice() {
    		return unitPrice;
    	}
    	public void setUnitPrice(Float unitPrice) {
    		this.unitPrice = unitPrice;
    	}
    	public Float getUnitAmount() {
    		return unitAmount;
    	}
    	public void setUnitAmount(Float unitAmount) {
    		this.unitAmount = unitAmount;
    	}
    	public String getNotes() {
    		return notes;
    	}
    	public void setNotes(String notes) {
    		this.notes = notes;
    	}
        
    }
    

    ③java导出excel方法

    package org;
    import java.io.FileOutputStream;
    import java.util.List;
    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.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.util.CellRangeAddress;
    public class ExportExcel {
    	public void getValue(List<WorkSheetDetail> userList,FileOutputStream fout){
    		  try{
    	            //1.创建工作簿
    	            HSSFWorkbook workbook = new HSSFWorkbook();
    	            //1.1创建合并单元格对象
    	            CellRangeAddress callRangeAddress = new CellRangeAddress(0,0,0,7);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddress1 = new CellRangeAddress(1,1,0,7);//起始行,结束行,起始列,结束列
    	            //班组与时间start
    	            CellRangeAddress callRangeAddress20 = new CellRangeAddress(2,2,0,2);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddress21 = new CellRangeAddress(2,2,3,4);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddress22 = new CellRangeAddress(2,2,5,7);//起始行,结束行,起始列,结束列
    	            //班组与时间end
    	            
    	            //标题
    	            CellRangeAddress callRangeAddress31 = new CellRangeAddress(3,4,0,0);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddress32 = new CellRangeAddress(3,4,1,1);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddress33 = new CellRangeAddress(3,4,2,2);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddress34 = new CellRangeAddress(3,3,3,4);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddress35 = new CellRangeAddress(3,4,5,5);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddress36 = new CellRangeAddress(3,4,6,6);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddress37 = new CellRangeAddress(3,4,7,7);//起始行,结束行,起始列,结束列
    	            
    	            //金额
    	            CellRangeAddress callRangeAddressnumber1 = new CellRangeAddress(userList.size()+5,userList.size()+5,0,2);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddressnumber2 = new CellRangeAddress(userList.size()+5,userList.size()+5,3,7);//起始行,结束行,起始列,结束列
    
    	            //负责人
    	            CellRangeAddress callRangeAddressPersion1 = new CellRangeAddress(userList.size()+6,userList.size()+6,0,2);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddressPersion2 = new CellRangeAddress(userList.size()+6,userList.size()+6,3,4);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddressPersion3 = new CellRangeAddress(userList.size()+6,userList.size()+6,5,7);//起始行,结束行,起始列,结束列
    
    	            //说明
    	            CellRangeAddress callRangeAddressinfo = new CellRangeAddress(userList.size()+7,userList.size()+7,0,7);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddressinfo1 = new CellRangeAddress(userList.size()+8,userList.size()+8,0,7);//起始行,结束行,起始列,结束列
    	            CellRangeAddress callRangeAddressinfo2 = new CellRangeAddress(userList.size()+9,userList.size()+9,0,7);//起始行,结束行,起始列,结束列
    
    	            //部项目经理部
    	            HSSFCellStyle headStyle = createCellStyle(workbook,(short)10,false,true);
    	            //派工单
    	            HSSFCellStyle erStyle = createCellStyle(workbook,(short)13,true,true);
    	            //班组和时间
    	            HSSFCellStyle sanStyle = createCellStyle(workbook,(short)10,false,false);
    	            //标题样式
    	            HSSFCellStyle colStyle = createCellStyle(workbook,(short)10,true,true);
    	            //内容样式
    	            HSSFCellStyle cellStyle = createCellStyle(workbook,(short)10,false,true);
    	            //2.创建工作表
    	            HSSFSheet sheet = workbook.createSheet("派单");
    	            //2.1加载合并单元格对象
    	            sheet.addMergedRegion(callRangeAddress);
    	            sheet.addMergedRegion(callRangeAddress1);
    	            sheet.addMergedRegion(callRangeAddress20);
    	            sheet.addMergedRegion(callRangeAddress21);
    	            sheet.addMergedRegion(callRangeAddress22);
    	            sheet.addMergedRegion(callRangeAddress31);
    	            sheet.addMergedRegion(callRangeAddress32);
    	            sheet.addMergedRegion(callRangeAddress33);
    	            sheet.addMergedRegion(callRangeAddress34);
    	            sheet.addMergedRegion(callRangeAddress35);
    	            sheet.addMergedRegion(callRangeAddress36);
    	            sheet.addMergedRegion(callRangeAddress37);
    	            sheet.addMergedRegion(callRangeAddressnumber1);
    	            sheet.addMergedRegion(callRangeAddressnumber2);
    	            sheet.addMergedRegion(callRangeAddressPersion1);
    	            sheet.addMergedRegion(callRangeAddressPersion2);
    	            sheet.addMergedRegion(callRangeAddressPersion3);
    	            sheet.addMergedRegion(callRangeAddressinfo);
    	            sheet.addMergedRegion(callRangeAddressinfo1);
    	            sheet.addMergedRegion(callRangeAddressinfo2);
    	            //设置默认列宽
    	            sheet.setDefaultColumnWidth(15);
    	            //3.创建行
    	            //3.1创建头标题行;并且设置头标题
    	            HSSFRow row = sheet.createRow(0);
    	            HSSFCell cell = row.createCell(0);
    	            //加载单元格样式
    	            cell.setCellStyle(headStyle);
    	            cell.setCellValue("xxxx项目部");
    	            
    	            HSSFRow rower = sheet.createRow(1);
    	            HSSFCell celler = rower.createCell(0);
    	            //加载单元格样式
    	            celler.setCellStyle(erStyle);
    	            celler.setCellValue("派 工 单");
    	            
    	            HSSFRow rowsan = sheet.createRow(2);
    	            HSSFCell cellsan = rowsan.createCell(0);
    	            HSSFCell cellsan1 = rowsan.createCell(3);
    	            HSSFCell cellsan2 = rowsan.createCell(5);
    	            //加载单元格样式
    	            cellsan.setCellStyle(sanStyle);
    	            cellsan.setCellValue("协作单位:x施工一堆");
    	            cellsan1.setCellStyle(sanStyle);
    	            cellsan1.setCellValue("");
    	            cellsan2.setCellStyle(sanStyle);
    	            cellsan2.setCellValue("时间:2017年 10月 20日");
    	            
    	            //3.2创建列标题;并且设置列标题
    	            HSSFRow row2 = sheet.createRow(3);
    	            String[] titles = {"序号","工作内容","用工总人数","工日数","","单价(元)","金额(元)","备注"};//""为占位字符串
    	            for(int i=0;i<titles.length;i++)
    	            {
    	                HSSFCell cell2 = row2.createCell(i);
    	                //加载单元格样式
    	                cell2.setCellStyle(colStyle);
    	                cell2.setCellValue(titles[i]);
    	            }
    	            
    	            HSSFRow rowfour = sheet.createRow(4);
    	            String[] titlefour = {"普工用工数","技工用工数"};
    	            for(int i=0;i<titlefour.length;i++)
    	            {
    	                HSSFCell cell2 = rowfour.createCell(i+3);
    	                //加载单元格样式
    	                cell2.setCellStyle(colStyle);
    	                cell2.setCellValue(titlefour[i]);
    	            }
    	            
    	            
    	            //4.操作单元格;将用户列表写入excel
    	            if(userList != null)
    	            {
    	            	int i=1;
    	                for(int j=0;j<userList.size();j++)
    	                {
    	                    //创建数据行,前面有两行,头标题行和列标题行
    	                    HSSFRow row3 = sheet.createRow(j+5);
    	                    HSSFCell cell0 = row3.createCell(0);
    	                    cell0.setCellStyle(cellStyle);
    	                    cell0.setCellValue(i++);
    	                    
    	                    HSSFCell cell1 = row3.createCell(1);
    	                    cell1.setCellStyle(cellStyle);
    	                    cell1.setCellValue(userList.get(j).getWorkCtx());
    	                    
    	                    HSSFCell cell2 = row3.createCell(2);
    	                    cell2.setCellStyle(cellStyle);
    	                    cell2.setCellValue(userList.get(j).getTotalHumanDays());
    	                    
    	                    HSSFCell cell3 = row3.createCell(3);
    	                    cell3.setCellStyle(cellStyle);
    	                    cell3.setCellValue(userList.get(j).getGwnNum());
    	                    
    	                    HSSFCell cell4 = row3.createCell(4);
    	                    cell4.setCellStyle(cellStyle);
    	                    cell4.setCellValue(userList.get(j).getTmnNum());
    	                    
    	                    HSSFCell cell5 = row3.createCell(5);
    	                    cell5.setCellStyle(cellStyle);
    	                    cell5.setCellValue(userList.get(j).getTotalHumanDays());
    	                    
    	                    HSSFCell cell6 = row3.createCell(6);
    	                    cell6.setCellStyle(cellStyle);
    	                    cell6.setCellValue(userList.get(j).getUnitAmount());
    	                    
    	                    HSSFCell cell7= row3.createCell(7);
    	                    cell7.setCellStyle(cellStyle);
    	                    cell7.setCellValue(userList.get(j).getUnitPrice());
    	                }
    	            }
    	            
    	            HSSFRow rownumber = sheet.createRow(userList.size()+5);
    	            HSSFCell cellnumber = rownumber.createCell(0);
    	            HSSFCell cellnumber1 = rownumber.createCell(3);
    	            //加载单元格样式
    	            cellnumber.setCellStyle(sanStyle);
    	            cellnumber.setCellValue("金额合计(大写)");
    	            cellnumber1.setCellStyle(sanStyle);
    	            cellnumber1.setCellValue("¥ 78 元; 大写:柒拾捌元整");
    
    	            HSSFRow rowpersion = sheet.createRow(userList.size()+6);
    	            HSSFCell cellpersion = rowpersion.createCell(0);
    	            HSSFCell cellpersion1 = rowpersion.createCell(3);
    	            HSSFCell cellpersion2 = rowpersion.createCell(5);
    
    	            //加载单元格样式
    	            cellpersion.setCellStyle(sanStyle);
    	            cellpersion.setCellValue("协作单位负责人:");
    	            cellpersion1.setCellStyle(sanStyle);
    	            cellpersion1.setCellValue("经办人:");
    	            cellpersion2.setCellStyle(sanStyle);
    	            cellpersion2.setCellValue("部门负责人:");
    	            
    	            HSSFRow rowinfo = sheet.createRow(userList.size()+7);
    	            HSSFCell cellinfo = rowinfo.createCell(0);
    	            cellinfo.setCellStyle(sanStyle);
    	            cellinfo.setCellValue("说明:1、本标工单一式两联,第一联为派工人(工长)存根,第二联用作结算。");
    	            
    	            HSSFRow rowinfo1 = sheet.createRow(userList.size()+8);
    	            HSSFCell cellinfo1 = rowinfo1.createCell(0);
    	            cellinfo1.setCellStyle(sanStyle);
    	            cellinfo1.setCellValue("2、本标工单必须在用工当日签认,否则不予认可;三日内交合同处汇总。");
    	            
    	            HSSFRow rowinfo2 = sheet.createRow(userList.size()+9);
    	            HSSFCell cellinfo2 = rowinfo2.createCell(0);
    	            cellinfo2.setCellStyle(sanStyle);
    	            cellinfo2.setCellValue("3、工日数填写精确到半个工日。");
    	            //5.输出
    	            workbook.write(fout);
    //	            workbook.close();
    	            //out.close();
    	        }catch(Exception e)
    	        {
    	            e.printStackTrace();
    	        }
    	}
    	
        /**
         * 
         * @param workbook
         * @param fontsize
         * @return 单元格样式
         */
        private static HSSFCellStyle createCellStyle(HSSFWorkbook workbook, short fontsize,boolean flag,boolean flag1) {
            // TODO Auto-generated method stub
            HSSFCellStyle style = workbook.createCellStyle();
            //是否水平居中
            if(flag1){
            	style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
            }
           
            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
            //创建字体
            HSSFFont font = workbook.createFont();
            //是否加粗字体
            if(flag){
                font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            }
            font.setFontHeightInPoints(fontsize);
            //加载字体
            style.setFont(font);
            return style;
        }
    }
    


    ④main方法

    package org;
    
    import java.io.FileOutputStream;
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainOut {
    	public static void main(String args[]){
    		//模拟部分数据
    		List<WorkSheetDetail> detail = new ArrayList<WorkSheetDetail>();
    
    		WorkSheetDetail d1 =new WorkSheetDetail("23",23f,43,34,243f,54f,"34");
    		WorkSheetDetail d2 =new WorkSheetDetail("23",23f,43,34,243f,54f,"34");
    		WorkSheetDetail d3 =new WorkSheetDetail("23",23f,43,34,243f,54f,"34");
    		WorkSheetDetail d4 =new WorkSheetDetail("23",23f,43,34,243f,54f,"34");
    		WorkSheetDetail d5 =new WorkSheetDetail("23",23f,43,34,243f,54f,"34");
    		detail.add(d1);
    		detail.add(d2);
    		detail.add(d3);
    		detail.add(d4);
    		detail.add(d5);
            try  
            {  
                FileOutputStream fout = new FileOutputStream("E:/students.xls");
        		new ExportExcel().getValue(detail, fout);
                fout.close();  
            }  
            catch (Exception e)  
            {  
                e.printStackTrace();  
            }  
    
    	}
    }
    

    ⑤截图

    展开全文
  • java导出excel合并单元格

    千次阅读 2018-12-31 13:17:32
    1、java导出excel用到POI所有jar包 ,大家可以直接到下面地址下载点击打开链接 2、导出excel的方法 package org; import java.io.FileOutputStream; import java.util.List; import org.apache.poi.hssf....
  • POI 导出excel文件下拉框问题 1.https://blog.csdn.net/sdaujsj1/article/details/81004209 java导出Excel合并单元格 2https://blog.csdn.net/datangxiajun/article/details/78308979
  • 主要介绍了Java导出excel合并同一列中相同内容的,需要的朋友可以参考下
  • //** * @Title: writeExcel * @Description: 生成excel方法 * @param filename(路径+文件名) , ... header 第一标题,List<SaAct> 数据 * @return 无 */ public void writeExcel(String filen...
  • Java导出Excel合并行、合并列

    千次阅读 2020-08-25 09:34:46
    //合并行 String[] rowKeys = {"NAME","DETAIL","Z_NAME","Z_DETAIL","",""};//需要合并列名,与key对应,不需要合并的列对应的数组位置列名为空字符串即可跳过 String[] rowValue = {"NAME","DETAIL","Z_NAME","Z...
  • java导出Excel 时候 相同行合并(可合并多列); 已测试通过;
  • java导出excel合并单元格及设置

    千次阅读 2019-04-23 15:16:12
    功能是导出表格 package checkout_excel; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; public class MainOut { public static void main(String args[]){ //...
  • 合并单元格代码: CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 1, 0, 0); sheet.addMergedRegion(cellRangeAddress); //加入边框 setBorderStyle(BorderStyle.THIN, cellRangeAddress, sheet);...
  • Java poi导出excel合并标题单元格

    万次阅读 2015-12-11 11:12:52
    Java poi导出excel合并标题单元格
  • 到出的数据中,如何合并相同的数据,格式如下: ![图片说明](https://img-ask.csdn.net/upload/201508/03/1438600476_655381.png)这段方法具体怎么写,请帮忙指教!
  • java poi excel导出合并行 需要注意的点是因为行是从0开始 list也是从0开始 开始行和结束行需要注意 int startrow=sheet.getLastRowNum(); sheet.addMergedRegion(new CellRangeAddress(startrow+1, (startrow+...
  • 我现在卡在了一个地方,就是我的导出已经实现了,但是我现在需要实现在导出的时候根据单元格数据去动态合并单元格的功能,这点不会卡着了,刚毕业没多久工作还没有一年才几个月,大老,我这些有点不会,你能帮我解答...
  • JAVA excel合并单元格原生poi 合并后的效果 直接上代码 (该方法为如果指定的单元格里面的值一致则进行合并,直接粘贴使用即可) * * @param sheet * @param colIdx 合并的列 * @param startRow 起始 * @...
  • JAVA基础 JAVA异常分类及处理 异常分类 异常的处理方式 Throw和throws的区别 JAVA反射 动态语言 反射机制概念 (运行状态中知道类所有的属性和方法) Java反射API 反射使用步骤(获取Class对象、调用对象方法) ...
  • Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright蕃薯耀 2017年9月13日 http://www.cnblogs.com/fanshuyao/ 直接上代码: import java.io....

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 7,679
精华内容 3,071
关键字:

java导出excel合并行

java 订阅