ITeye博客

JXT 导出数据到EXCEL

rainyear · 2011-10-25 10:30 · Java基础 · 非技术 · Markdown

1. public class ExportExcel {

/**
 * @param List封装着Object的列表          
 * @param title每个sheet里的标题       	 */
private final static Logger log = Logger.getLogger(ExportExcel.class.getName());

public static InputStream getExcelInputStream(List<String> list, String title) {
	ByteArrayOutputStream out = new ByteArrayOutputStream();// 将OutputStream转化为InputStream
	writeExcel(out, list, title);
	return new ByteArrayInputStream(out.toByteArray());
}

public static void writeExcel(OutputStream out, List<String> list, String title) {
	try {
		WritableWorkbook workbook = Workbook.createWorkbook(out);
		WritableSheet ws = workbook.createSheet("sheet 1", 0);
		int rowNum = 0; // 要写的行,第一行是从0开始,以此类推
		if (title != null) {
			putRow(ws, 0, title); 
			rowNum = 1;
		}
		for (int i = 0; i < list.size(); i++, rowNum++) { //数据写入Excel
			Object cells = (Object) list.get(i);
			putRow(ws, rowNum, cells); 
		}
		workbook.write();
		workbook.close();  
	} catch (RowsExceededException e) {
		log.error(e);
	} catch (WriteException e) {
		log.error(e);
	} catch (IOException e) {
		log.error(e);
	}
}

private static void putRow(WritableSheet ws, int rowNum, Object cells)
		throws RowsExceededException, WriteException {
	for (int j = 0; j < cells.length; j++) {
		Label cell = new Label(j, rowNum, "" + cells);
		ws.addCell(cell);
	}
}

}

  1. SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); excelName = "Products_Export_"+ df.format(new java.util.Date()) + ".xls";//导出Excel文件名 List rowList=pageBean.getRows();//导出的记录 List extelDataList=new ArrayList(); for(int i=0;i<rowList.size();i++){ extelDataList.add(data);//要写入Excel的数据 } String title = { };//Excel标题 excelStream=ExportExcel.getExcelInputStream(extelDataList,title);

3>

application/vnd.ms-excel

excelStream

attachment;filename="${excelName}"
1024

\download 1000

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。