精华内容
下载资源
问答
  • 需求:用户在前台页面点击批量导出单据,实现下载对应批量单据excel文件压缩包功能 实现思路:先利用java poi工具类包中的Workbook类生成填充excel对象,然后用Workbook中的write方法将excel对象写入到输入流...

    需求:用户在前台页面点击批量导出单据,实现下载对应批量单据excel文件压缩包功能

    实现思路:先利用java poi工具类包中的Workbook类生成填充excel对象,然后用Workbook中的write方法将excel对象写入到输入流InputStream中,创建压缩文件对象ZipEntry,然后创建ZipOutputStream压缩包输出流对象,因为是要实现前台页面下载功能,所以压缩包流对象要包装response.getOutputStream后台响应输出流,调用ZipOutputStream压缩包流putNextEntry()方法,将文件压缩对象ZipEntry放入到ZipOutputStream压缩包输出流中,然后将excel输入流InputStream写到ZipOutputStream压缩包输出流中,循环进行上述操作,即可实现批量单据excel打包下载

    代码部分:

    TemplateExportParams params = new TemplateExportParams(templatePath);
    //List<File> srcfile = new ArrayList<File>();  //声明一个集合,用来存放多个Excel文件路径及名称
        String filename = (String) mapData.get("filename");
        //生成excel对象
        Workbook workbook = ExcelExportUtil.exportExcel(params, mapData);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        workbook.write(bos);
        byte[] barray = bos.toByteArray();
        InputStream is = new ByteArrayInputStream(barray);
        is.close();
        ZipEntry zipEntry = new ZipEntry(filename);
        Map map = new HashMap();
        map.put("stream",is);
        map.put("zip",zipEntry);
    return map;
    String pathname=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    //File zipfile = new File(pathname);
    response.setCharacterEncoding("UTF-8"); // 重点突出
    response.setContentType("application/zip");
    // 对文件名进行编码处理中文问题
    pathname = new String(pathname.getBytes(), StandardCharsets.UTF_8);
    //设置前台下载压缩包名
    response.setHeader("Content-Disposition", "attachment;filename=" + pathname);
    response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    byte[] buf = new byte[1024];
    try {
        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        for (int i = 0; i < zipEntry.size(); i++) {
            ZipEntry zipEntryDetail = (ZipEntry)zipEntry.get(i).get("zip");
            InputStream in = (InputStream)zipEntry.get(i).get("stream");
            // Add ZIP entry to output stream.
            out.putNextEntry(zipEntryDetail);
            // Transfer bytes from the file to the ZIP file
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            // Complete the entry
            out.closeEntry();
            in.close();
        }
        out.close();

     

     

    展开全文
  • 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,以压缩包下载

    千次阅读 热门讨论 2018-06-26 15:21:39
    需求:一次请求,导出多个excel 思路: 1.java servlet一个请求,只能返回一个输出流,所以一次只能导出一个excel; 2.如果一次需要导出多个excel,可以在本地生成多个excel,然后压缩成压缩包,然后下载压缩包; 步骤: 1...

    需求:一次请求,导出多个excel
    思路:
    1.java servlet一个请求,只能返回一个输出流,所以一次只能导出一个excel;
    2.如果一次需要导出多个excel,可以在本地生成多个excel,然后压缩成压缩包,然后下载压缩包;
    步骤:
    1.在本地创建一个零时文件夹,将多个excel生成到该文件夹下;
    2.将该文件夹压缩,导出;
    3.将该文件夹删除;

    上代码:

    //以模板形式生成excel
    @RequestMapping(value = "映射路径")
    public void exportDetail(HttpServletResponse response, HttpServletRequest request)throws ParseException, ParsePropertyException, InvalidFormatException, IOException {
        // 模板在项目存放位置
            String fileRootPath = request.getSession().getServletContext().getRealPath("/templates");
        // 模板文件名称
        String fileName = "";
        // 将excel导出的文件位置
        String filePath = 在本地创建好的文件夹路径 + File.separator;
        // 得到此路径下文件
        File fileDir = new File(filePath);
        //创建文件夹
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
       // 用于存放生成的excel文件名称
        List<String> fileNames = new ArrayList<String>();
        // 导出Excel文件路径
        String fullFilePath = "";
        //输入流
        InputStream in = null;
        //输出流
        FileOutputStream os = null;
        //循环导出excel到临时文件夹中
        for (int i = 0; 根据需求亲确定导出几次; i++) {
        // 往excel填入内容
        Map<String, Object> bean = new HashMap<String, Object>();
        bean.put("需要遍历的内容", xxxx);
        //每次导出的excel的文件名
        String fileNameS = "xxxxx.xls";
        if (bean != null) {
        //XLSTransformer生成excel文件
        XLSTransformer transformer = new XLSTransformer();
        in = new FileInputStream(new File(fileRootPath + File.separator + fileName));
        HSSFWorkbook workbook;
        // 设置sheet页名称
        String sheetName = "详细";
        workbook = (HSSFWorkbook) transformer.transformXLS(in, bean);
        // 设置sheet页名称
        workbook.setSheetName(0, sheetName);
        // 导出excel的全路径
        fullFilePath = filePath + File.separator + fileNameS;
        fileNames.add(fullFilePath);
        os = new FileOutputStream(fullFilePath);
        // 写文件
        workbook.write(os);
        }
        //清空流缓冲区数据
        os.flush();
        //关闭流
        os.close();
        in.close();
        os = null;
        }
    
        //导出压缩文件的全路径  
        String zipFilePath = filePath + "压缩文件名"+".zip";
        //导出zip
        File zip = new File(zipFilePath);
        //将excel文件生成压缩文件  
        File srcfile[] = new File[fileNames.size()];    
         for (int j = 0, n1 = fileNames.size(); j < n1; j++) {    
             srcfile[j] = new File(fileNames.get(j));    
         }    
           ZipFiles(srcfile, zip);
         response.setContentType("application/zip");
            response.setHeader("Location",zip.getName());
            response.setHeader("Content-Disposition", "attachment; filename=" + zip.getName());  
            OutputStream outputStream = response.getOutputStream();
            InputStream inputStream = new FileInputStream(zipFilePath);
            byte[] buffer = new byte[1024];
            int i = -1;
            while ((i = inputStream.read(buffer)) != -1) {
               outputStream.write(buffer, 0, i);
             }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            outputStream = null;
    
           try {  
                delAllFile(filePath); // 删除完里面所有内容  
                filePath = filePath.toString();  
                java.io.File myFilePath = new java.io.File(filePath);  
                myFilePath.delete(); // 删除空文件夹  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }
    
    
        //压缩文件    
        public void ZipFiles(File[] srcfile, File zipfile) {    
            byte[] buf = new byte[1024];    
            try {    
                ZipOutputStream out = new ZipOutputStream(new FileOutputStream(    
                        zipfile));    
                for (int i = 0; i < srcfile.length; i++) {    
                    FileInputStream in = new FileInputStream(srcfile[i]);    
                    out.putNextEntry(new ZipEntry(srcfile[i].getName()));    
                    int len;    
                    while ((len = in.read(buf)) > 0) {    
                        out.write(buf, 0, len);    
                    }    
                    out.closeEntry();    
                    in.close();    
                }    
                out.close();    
            } catch (IOException e) {    
                e.printStackTrace();    
            }    
        }  
    
    
        /*** 
         * 删除指定文件夹下所有文件 
         *  
         * @param path 文件夹完整绝对路径 
         * @return 
         */  
        public static  boolean delAllFile(String path) {  
            boolean flag = false;  
            File file = new File(path);  
            if (!file.exists()) {  
                return flag;  
            }  
            if (!file.isDirectory()) {  
                return flag;  
            }  
            String[] tempList = file.list();  
            File temp = null;  
            for (int i = 0; i < tempList.length; i++) {  
                if (path.endsWith(File.separator)) {  
                    temp = new File(path + tempList[i]);  
                } else {  
                    temp = new File(path + File.separator + tempList[i]);  
                }  
                if (temp.isFile()) {  
                    temp.delete();  
                }  
                if (temp.isDirectory()) {  
                    delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件  
                    flag = true;  
                }  
            }  
            return flag;  
        }  

    搞定!

    展开全文
  • 最近的项目有一个导出汇总数据的要求,考虑到用户软件的差异,所以要分别导出xls以及xlsx并且打包提供下载,所以有了这博客,代码如下。 实现思路: 获取需要导出的数据; 生成对应的xls、xlsx文件流; 生成...

    最近的项目有一个导出汇总数据的要求,考虑到用户软件的差异,所以要分别导出xls以及xlsx并且打包提供下载,所以有了这个博客,代码如下。

    实现思路:

    1. 获取需要导出的数据;
    2. 生成对应的xls、xlsx文件流;
    3. 生成对应的zip文件,提供下载。

    代码主要使用到了POI以及Hutool解压模块。

     

     

    /**
    	 * 利用传入的数据,生成对应的xls文件
    	 * 
    	 * @param data       需要导出的数据
    	 * @param sheetName  sheet的名字
    	 * @param titleValue excel主题(例如第一行显示:“2018-10月销售汇总”)
    	 * @param headArr    标题
    	 * 
    	 * @return 生成的03excel工作簿
    	 */
    	public static <T> HSSFWorkbook exportDataTo03(List<T> data, String sheetName, String titleValue, String[] headArr)
    			throws IOException, IllegalArgumentException, IllegalAccessException {
    		// 新建excel
    		HSSFWorkbook wb = new HSSFWorkbook();
    
    		// 新建sheet
    		HSSFSheet sheet = wb.createSheet(sheetName);
    		// 1.1创建合并单元格对象
    		CellRangeAddress callRangeAddress = new CellRangeAddress(0, 0, 0, headArr.length - 1);
    		sheet.addMergedRegion(callRangeAddress);
    
    		// 新建第一行表头
    		HSSFRow titleRow = sheet.createRow(0);
    		titleRow.setHeightInPoints(50);
    		HSSFFont titleFont = wb.createFont();
    		titleFont.setBold(true);
    		titleFont.setFontName("微软雅黑");
    		titleFont.setFontHeightInPoints((short) 35);
    		// 样式
    		HSSFCellStyle titleStyle = wb.createCellStyle();
    		// 剧中
    		titleStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
    		titleStyle.setFont(titleFont);
    
    		HSSFCell titleCell = titleRow.createCell(0);
    		titleCell.setCellStyle(titleStyle);
    		titleCell.setCellValue(titleValue + "xxx");
    
    		HSSFCellStyle hearStyle = wb.createCellStyle();
    		hearStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
    		HSSFFont headFont = wb.createFont();
    		headFont.setBold(true);
    		headFont.setFontName("微软雅黑");
    		headFont.setFontHeightInPoints((short) 50);
    
    		HSSFRow headRow = sheet.createRow(1);
    		headRow.setHeightInPoints(30);
    		for (int i = 0; i < headArr.length; i++) {
    			HSSFCell headCell = headRow.createCell(i);
    			headCell.setCellStyle(hearStyle);
    			headCell.setCellValue(headArr[i]);
    			// TODO 这里要根据对应的列名设置对应的宽度,更美观一点。我这里偷懒直接所有的设置一样的
    			sheet.setColumnWidth(i, 256 * 30);
    		}
    
    		HSSFCellStyle valueStyle = wb.createCellStyle();
    		valueStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
    		HSSFFont valueFont = wb.createFont();
    		valueFont.setFontName("微软雅黑");
    		valueFont.setFontHeightInPoints((short) 15);
    		valueStyle.setFont(valueFont);
    
    		// 根据反射获取私有字段,与列名匹配,对应的话就插入对应数据
    		for (int valueIndex = 0; valueIndex < data.size(); valueIndex++) {
    			HSSFRow valueRow = sheet.createRow(valueIndex + 2);
    			valueRow.setHeightInPoints(30);
    			Class c = data.get(valueIndex).getClass();
    			Field[] fields = c.getDeclaredFields();
    			for (int i = 0; i < fields.length; i++) {
    				NoExport amazonFiled = fields[i].getAnnotation(NoExport.class);
    				if (amazonFiled != null && amazonFiled.value() == false) {
    					continue;
    				}
    				fields[i].setAccessible(true);
    				String fidldName = fields[i].getName();
    				for (int j = 0; j < headArr.length; j++) {
    					String headName = headArr[j];
    					if (fidldName.trim().equalsIgnoreCase(headName.trim())) {
    						HSSFCell valueCell = valueRow.createCell(j);
    						valueCell.setCellStyle(valueStyle);
    						valueCell.setCellValue(fields[i].get(data.get(valueIndex)) + "");
    						break;
    					}
    				}
    			}
    		}
    		return wb;
    	}

     

     

    	/**
    	 * 利用传入的数据,生成对应的xlsx文件
    	 * 
    	 * @param data       需要导出的数据
    	 * @param sheetName  sheet的名字
    	 * @param titleValue excel主题(例如第一行显示:“2018-10月销售汇总”)
    	 * @param headArr    标题
    	 * 
    	 * @return 生成的07excel工作簿
    	 */
    	public static <T> XSSFWorkbook exportDataTo07(List<T> data, String sheetName, String titleValue, String[] headArr)
    			throws IOException, IllegalArgumentException, IllegalAccessException {
    		// 新建excel
    		XSSFWorkbook wb = new XSSFWorkbook();
    
    		// 新建sheet
    		XSSFSheet sheet = wb.createSheet(sheetName);
    		// 1.1创建合并单元格对象
    		CellRangeAddress callRangeAddress = new CellRangeAddress(0, 0, 0, headArr.length - 1);
    		sheet.addMergedRegion(callRangeAddress);
    
    		// 新建第一行表头
    		XSSFRow titleRow = sheet.createRow(0);
    		titleRow.setHeightInPoints(50);
    		XSSFFont titleFont = wb.createFont();
    		titleFont.setBold(true);
    		titleFont.setFontName("微软雅黑");
    		titleFont.setFontHeightInPoints((short) 35);
    		// 样式
    		XSSFCellStyle titleStyle = wb.createCellStyle();
    		// 剧中
    		titleStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
    		titleStyle.setFont(titleFont);
    
    		XSSFCell titleCell = titleRow.createCell(0);
    		titleCell.setCellStyle(titleStyle);
    		titleCell.setCellValue(titleValue + "xxx");
    
    		XSSFCellStyle hearStyle = wb.createCellStyle();
    		hearStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
    		XSSFFont headFont = wb.createFont();
    		headFont.setBold(true);
    		headFont.setFontName("微软雅黑");
    		headFont.setFontHeightInPoints((short) 50);
    
    		XSSFRow headRow = sheet.createRow(1);
    		headRow.setHeightInPoints(30);
    		for (int i = 0; i < headArr.length; i++) {
    			XSSFCell headCell = headRow.createCell(i);
    			headCell.setCellStyle(hearStyle);
    			headCell.setCellValue(headArr[i]);
    			sheet.setColumnWidth(i, 256 * 30);
    		}
    
    		XSSFCellStyle valueStyle = wb.createCellStyle();
    		valueStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
    		XSSFFont valueFont = wb.createFont();
    		valueFont.setFontName("微软雅黑");
    		valueFont.setFontHeightInPoints((short) 15);
    		valueStyle.setFont(valueFont);
    
    		for (int valueIndex = 0; valueIndex < data.size(); valueIndex++) {
    			XSSFRow valueRow = sheet.createRow(valueIndex + 2);
    			valueRow.setHeightInPoints(30);
    			Class c = data.get(valueIndex).getClass();
    			Field[] fields = c.getDeclaredFields();
    			for (int i = 0; i < fields.length; i++) {
    				NoExport amazonFiled = fields[i].getAnnotation(NoExport.class);
    				if (amazonFiled != null && amazonFiled.value() == false) {
    					continue;
    				}
    				fields[i].setAccessible(true);
    				String fidldName = fields[i].getName();
    				for (int j = 0; j < headArr.length; j++) {
    					String headName = headArr[j];
    					if (fidldName.trim().equalsIgnoreCase(headName.trim())) {
    						XSSFCell valueCell = valueRow.createCell(j);
    						valueCell.setCellStyle(valueStyle);
    						valueCell.setCellValue(fields[i].get(data.get(valueIndex)) + "");
    						break;
    					}
    				}
    			}
    		}
    		return wb;
    	}
    /**
    	 * 把传入的工作簿文件转成输入流
    	 * 
    	 * @param workbooks 工作簿文件
    	 * @return 文件流list
    	 */
    	public static List<ByteArrayOutputStream> workBook2Stream(Workbook... workbooks) throws IOException {
    		List<ByteArrayOutputStream> list = new LinkedList<ByteArrayOutputStream>();
    		for (Workbook obj : workbooks) {
    			ByteArrayOutputStream os = new ByteArrayOutputStream();
    			obj.write(os);
    			list.add(os);
    			obj.close();
    		}
    		return list;
    	}
    
    	/**
    	 * 压缩文件
    	 * 
    	 * @param workBook  生成的03工作簿
    	 * @param xworkWork 生成的07工作簿
    	 * @param fileNames 被压缩的文件名称
    	 * 
    	 * @return File 生成的压缩包文件
    	 * 
    	 * @throws IOException
    	 * 
    	 */
    	public static File zipFile(HSSFWorkbook workBook, XSSFWorkbook xworkWork, String[] fileNames) throws Exception {
    		// 写入输入流
    		List<ByteArrayOutputStream> workList = workBook2Stream(workBook, xworkWork);
    		InputStream[] is = new InputStream[workList.size()];
    		int step = 0;
    		for (ByteArrayOutputStream bs : workList) {
    			byte[] content = bs.toByteArray();
    			ByteArrayInputStream bt = new ByteArrayInputStream(content);
    			is[step] = bt;
    			step++;
    		}
    		// 获取项目路径
    		String rootPath = BusinessUtils.class.getClassLoader().getResource("").getPath();
    		// 创建临时文件tempFile
    		File zipFile = new File(rootPath + "/tempFile.zip");
    		if (!zipFile.exists()) {
    			zipFile.createNewFile();
    		}
    
    		zipFile = ZipUtil.zip(zipFile, fileNames, is);
    
    		// 关闭流
    		for (ByteArrayOutputStream steam : workList) {
    			IoUtil.close(steam);
    		}
    
    		for (InputStream steam : is) {
    			IoUtil.close(steam);
    		}
    		return zipFile;
    	}
    

    下载:

    File zipFile = BusinessUtils.zipFile(workBook, xworkWork, fileNames);
    			String downloadFileName = URLEncoder.encode("XX商户XX公司XXXX报税单销售汇总信息.zip", "UTF-8");
    			response.setHeader("content-type", "application/octet-stream");
    			response.setContentType("application/x-execl");
    			response.setHeader("Content-Disposition",
    					"attachment;filename=" + new String((downloadFileName).getBytes(), "UTF-8"));
    			// 读取文件
    			InputStream in = new FileInputStream(zipFile);
    			ServletOutputStream outputStream = response.getOutputStream();
    			// 写文件
    			int b;
    			while ((b = in.read()) != -1) {
    				outputStream.write(b);
    			}
    			in.close();
    			outputStream.close();
    			//删除临时文件
    			zipFile.delete();

    没了。

    效果如下:

    展开全文
  • java导出多个excel压缩zip下载

    千次阅读 2016-03-01 10:29:12
    package com.dianping.emidas.activity.biz.utils; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.Fil
  • 解决JAVA导出大数据的EXCEL文件

    万次阅读 热门讨论 2015-10-29 11:11:53
    在工作中遇到了要导出30万条数据的excel文件,写了一工具类。如下: import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans....
  • POI导出多个Excel文件,生成压缩文件

    千次阅读 2018-01-15 10:51:38
    当需要导出的sheet数超过255个时,比较好的办法是将多个Excel文件压缩成.zip文件再导出 步骤:1 将需要导出的表封装到listBean中   2 将list中表每隔255个sheet导出到一个Excel文件   3 将Excel文件生成压缩...
  • 将MySQL数据库中的多个导出到Excel文件,并在一个Excel文件中以多个sheet的形式存储下来。 1、建立Excel文件,并获取数据表数据: private static void process(String[] sqls) { Connection conn = ...
  • * 导出支付宝批量支付文件excel * * @param name * @param begintime * @param endtime * @param p * @param l * @param k * @param request * @param response */ @RequestMapping(...
  • java导出多个excel并打成zip包

    千次阅读 2017-12-12 16:20:16
    这里主要是要针对数据量过大,通过生成多个excel文件并打成一个zip压缩包提供下载.   压缩excel的类 ZipUtil:   Java代码  import java.io.*;  import java.util.*;  import java.util.zip....
  • // 导出,此处只封装了浏览器下载方式 // 调用downloadExcel,返回输出流给客户端 String fileName = (String) map2.get("name") + ".xlsx"; excel.downloadExcel(response, fileName); } } public void download...
  • jxl实现导出excel代码: 使用jxl导出的xls文件,格式不兼容office 2013,兼容WPS、office 2007 合并单元格使用mergeCells(a,b,c,d)方法:a.单元格的列号,b.单元格的行号,c.从单元格[a,b]起,向下合并的列数,d.从...
  • Java使用poi导出excel文件包含多个sheet

    千次阅读 2019-01-08 10:08:18
    最近一次小需求要求对一个页面的两个报表通过点击一个导出按钮导出到一个excel中,当然,是要求在一个excel中建立多个sheet来保存两个报表的数据,否则全部放置在一个报表中就没有意义了,记录一下,以免下次使用CV...
  • Java POI导入导出Excel文件

    万次阅读 多人点赞 2019-06-12 21:39:41
    Java POI Excel导入导出Excel文件 一、导入pom文件(版本号一定要相同,不然会报错) <!--读取excel文件--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>...
  • 前言:2020年第一篇文章,就写这两天工作中遇到的这个小需求吧,导出多excel,每个excel多个sheet页,需要把相同格式的excel的sheet页合并。2020年写出更优质的文章,让大家都能从中学到更多的知识。 一、java...
  • java 导出excel多个sheet

    万次阅读 2019-03-01 17:03:44
    java 导出excel 多个sheet 废话不多说了,直接上代码,有需要的盆友,可以看看。@TOC @RequestMapping("/exportAllyScoreCount") public void exportAllyScoreCount(HttpServletRequest request,...
  • Java导出Excel表格出现文件损坏异常解决方案问题出现 问题出现 本人遇到这问题,由于是第一次见,感觉无从下手.但是导出功能很常见,做的也很,只有这出现了文件损坏,那很可能是代码写的有问题. 出现损坏的.xls...
  • java技术--导出多个excel并打成zip包

    千次阅读 2019-09-03 11:07:03
    1.主要是要针对数据量过大,通过生成多个excel文件并打成一个zip压缩包提供下载 2.代码如下: import java.io.; import java.util.; import java.util.zip.ZipOutputStream; import java.util.zip.ZipEntry; import ...
  • java导出多excel功能

    千次阅读 2019-11-18 09:40:20
    /** * 导出 * * @return * @throws IOException */ @RequestMapping(value = "/export", produces = "application/json; charset=utf-8") public Map<String, Object> export...
  • Java导出数据到Excel

    万次阅读 多人点赞 2017-07-18 11:56:05
    Java操作Excel数据表,导出工具类,让导出更便捷!
  • 个excel表中到数据记录不能超过50条 碰过的坑:原先我发出的是ajax请求,然后请求成功却返回的都是乱码!我是想要下载文件啊!!!  ajax请求,响应的是文本数据,所以下载文件不能用ajax请求!用什么呢?用...
  • java中导入导出Excel文件

    千次阅读 2012-09-20 14:03:43
    java中导入导出Excel文件 一.POI简介 Jakarta POI 是apache的子项目,目标是处理ole2对象。它提供了一组操纵Windows文档的Java API 目前比较成熟的是HSSF接口,处理MS Excel(97-2002)对象。它不象我们仅仅...
  • Java导出Excel文件如何实现? 下面分为两段供各位测试,要是不懂或者实在不行可以评论一下,看到我会回复的 jar这些你们可以自己找,用maven也就是复制粘贴的事。 下面的链接是封装好的Excel文件导入导出的样式跟...
  • Java导出数据到Excel表格 今天是2020年2月14日,首先祝各位情人节快乐 下面言归正传开始正文。 在后台管理系统中经常会有导出数据到Excel表格的功能需求,这功能是难以规避的,而且这也是一非常使用且人性化的一...
  • java导出Excel多个sheet

    千次阅读 2017-08-14 10:05:16
    做数据报表的时候,有时候需要将一组数据,导出到一个Excel多个sheet中。 001 4 编号1 001 6 编号1 合计 10 编号1 002 5 编号2 002 5 编号2 合计 10 编号2 003 7

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 20,785
精华内容 8,314
关键字:

java导出多个excel文件

java 订阅