浏览 4814 次
锁定老帖子 主题:WEB中以cvs格式导出数据
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
|
|
---|---|
作者 | 正文 |
发表时间:2013-04-19
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.lang.reflect.Field; import java.util.List; import jxl.Workbook; import jxl.format.Colour; import jxl.write.Label; import jxl.write.WritableCellFormat; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; /** * 导出文件工具类 */ public class ExportUtil { /** * 创建TXT或者CSV文件 * * @param list 查询出的结果 * @param head 表头 * @param proerty 需要导出的列(与head对应) * @param fileName 文件名 * @return * @throws Exception */ public static File createTxtFile(List list, List<String> head, List<String> proerty, String fileName) throws Exception { File file = new File(fileName); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); StringBuilder sb = new StringBuilder(); for (String str : head) { sb.append("\t" + str + ","); } sb.append("\r\n"); Long row = 0L; for (Object obj : list) { Class className = obj.getClass(); // 反射所有字段 @SuppressWarnings("unused") Field[] fields = className.getDeclaredFields(); for (String str : proerty) { // 若该字段是需要导出的字段则写入Excel Object o = ReflectUtils.getProertyValue(obj, str); String value = o == null ? "" : o.toString(); // 设置cell的值 sb.append("\t" + value + ","); } sb.append("\r\n"); if (row % 1000 == 0) { out.write(sb.toString().getBytes(LX100Constant.CHAR_SET)); out.flush(); sb = new StringBuilder(); } } out.write(sb.toString().getBytes(LX100Constant.CHAR_SET)); out.flush(); out.close(); return file; } /** * 创建excel文件 * * @param list * @param head * @param proerty * @param fileName * @return * @throws Exception */ public static File createExcel(List list, List<String> head, List<String> proerty, String fileName) throws Exception { // 创建输出文件 File file = new File(fileName); int line = 0; int row = 0; int sheetNum = 1; // 表头格式 WritableCellFormat wcfF = new jxl.write.WritableCellFormat(); wcfF.setAlignment(jxl.format.Alignment.CENTRE); wcfF.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); @SuppressWarnings("unused") Colour olour; wcfF.setBackground(Colour.LIGHT_ORANGE); WritableWorkbook wwb = Workbook.createWorkbook(file); WritableSheet ws = wwb.createSheet("第" + sheetNum + "页", sheetNum); // 设置冻结首行 ws.getSettings().setVerticalFreeze(1); ws.getSettings().setFitWidth(100); // 数据格式 WritableCellFormat dateDcfF = new jxl.write.WritableCellFormat(); dateDcfF.setWrap(true); dateDcfF.setAlignment(jxl.format.Alignment.CENTRE); dateDcfF.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 控制列宽 ws.setColumnView(0, 10); ws.setColumnView(1, 18); ws.setColumnView(2, 18); ws.setColumnView(3, 18); ws.setColumnView(4, 18); ws.setColumnView(5, 25); ws.setColumnView(6, 18); ws.setColumnView(7, 18); ws.setColumnView(8, 18); ws.setColumnView(9, 18); ws.setColumnView(10, 18); ws.setColumnView(11, 18); ws.setColumnView(12, 18); ws.setColumnView(13, 18); ws.setColumnView(14, 18); ws.setColumnView(15, 18); sheetNum++; // 写入表头 for (String str : head) { Label label = new Label(line, 0, str, wcfF); ws.addCell(label); line++; } row++; // 写入数据 for (Object obj : list) { line = 0; Class className = obj.getClass(); // 反射所有字段 Field[] fields = className.getDeclaredFields(); for (String str : proerty) { for (Field field : fields) { // 若该字段是需要导出的字段则写入Excel if (str.equals(field.getName())) { // 修改相应filed的权限 boolean accessFlag = field.isAccessible(); field.setAccessible(true); // 读取对象中相应的属性的值 String value = field.get(obj).toString(); if (str.equals("commendTime")) { value = field.get(obj).toString().substring(0, 19); } // 设置cell的值 Label label = new Label(line, row, value, dateDcfF); ws.addCell(label); // 恢复相应field的权限 field.setAccessible(accessFlag); line++; } } } row++; // 行数超过10000行是数据放入下一个sheet if (row % 10000 == 0) { // 设置标题格式 line = 0; row = 0; ws = wwb.createSheet("第" + sheetNum + "页", sheetNum); // 设置冻结首行 ws.getSettings().setVerticalFreeze(1); // 控制列宽 ws.setColumnView(0, 10); ws.setColumnView(1, 18); ws.setColumnView(2, 18); ws.setColumnView(3, 18); ws.setColumnView(4, 18); sheetNum++; // 再次写入表头 for (String str : head) { Label label = new Label(line, 0, str, wcfF); ws.addCell(label); line++; } row++; } } // 写入数据并关闭文件 wwb.write(); wwb.close(); return file; } } POJO实体类 /** * 售后信息 */ public class FreeCallInfo { //商品ID private Long goodsId; // 机型 private String goodsName; //县公司Id private Long cityId; // 县公司名称 private String cityName; // 分公司Id private Long countyId; / 分公司名称 private String countyName; // 数量 private Long maintainNumber; // 修复方式 private String maintainType; //维修方式 private Long auditIsMaintain; //get、set } 查找数据的方法: public List<FreeCallInfo> query(Long cityId, Long countyId, Long mainType, String keyWord, String startTime, String endTime) { Object[] objs = null; StringBuilder sb = new StringBuilder( " select gi.goods_name as goodsName, " + "case" + " when fm.audit_is_machine = 0 then" + " '维修'" + " when fm.audit_is_machine = 1 then " + " '换机'" + " when fm.audit_is_machine = 2 then " + " '丢失'" + " end as maintainType," + "count(fm.goods_id) as maintainNumber" + " from erp_freecall_monitor fm" + " left join erp_goods_info gi" + " on fm.goods_id = gi.id" + " left join erp_organisation oo" + " on oo.id = fm.org_id" + " left join erp_dim_county dc" + " on oo.county_id = dc.county_id" + " left join erp_dim_city cc" + " on cc.city_id = dc.city_id " + " where fm.record_status = 2 "); if (mainType == 3) { objs = new Object[] { cityId, countyId, keyWord, startTime, endTime }; sb.append("and oo.city_id = ? and oo.county_id = ? and gi.goods_name like ? "); } else { objs = new Object[] { cityId, countyId, mainType, keyWord, startTime, endTime }; sb.append("and oo.city_id = ? and oo.county_id = ? and fm.audit_is_machine = ? and gi.goods_name like ? "); } sb.append("and to_char(fm.maintain_time, 'yyyy-MM-dd') >= ? " + "and to_char(fm.maintain_time, 'yyyy-MM-dd') <= ? " ); sb.append("group by gi.goods_name, fm.audit_is_machine"); List list = (List) this.getJdbcTemplate().query(sb.toString(), objs,new RowMapperResultSetExtractor(new RowMapper() { public Object mapRow(ResultSet res, int arg1) throws SQLException { FreeCallInfo fc = new FreeCallInfo(); fc.setGoodsName(res.getString("goodsName")); fc.setMaintainType(res.getString("maintainType")); fc.setMaintainNumber(res.getLong("maintainNumber")); return fc; } })); return list; } 页面的导出按钮: <input type="button" value="导出" <s:if test="pagination.total == 0">disabled="disabled"</s:if> onclick="window.location='<%=basePath%>afterSalesAction!countyExportMaintainInfo.action?mainType=${mainType}&keyWord=${keyWord}&startTime=${startTime}&endTime=${endTime}'" /> 导出cvs的action: /** * 县公司导出售后维修报表 */ public String countyExportMaintainInfo() { try { freeCallInfolList = freeCallMonitorService.query(user.getOrganisation().getCityId(), user.getOrganisation().getCountyId(), Long.valueOf(mainType), keyWord, startTime, endTime); String path = this.getServletContext().getRealPath("/"); fileName = new String("县公司售后维修报表统计.CSV".getBytes(LX100Constant.CHAR_SET), "ISO8859_1"); tmpFileName = "temp.csv"; List<String> head = new ArrayList<String>(); head.add("机型"); head.add("维修方式"); head.add("数量"); List<String> proerty = new ArrayList<String>(); proerty.add("goodsName"); proerty.add("maintainType"); proerty.add("maintainNumber"); File file = ExportUtil.createTxtFile(freeCallInfolList, head, proerty, path + tmpFileName); inputStream = new FileInputStream(file); log.info("用户导出县公司售后维修报表成功"); } catch (Exception e) { log.error("用户导出县公司售后维修报表异常,创建文件异常{}", new Object[] { e }); } return "export_success"; } 最后还要在sturts.xml中配置: <result name="export_success" type="stream"> <param name="inputName">inputStream</param> <param name="contentType">application/octet-stream</param> <param name="contentDisposition">attachment;filename="${fileName}"</param> <param name="bufferSize">500000</param> </result> 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |