import java.io.IOException;import java.io.OutputStream;import java.lang.reflect.Field;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import javax.servlet.http.HttpServletResponse;import org.apache.commons.lang3.StringUtils;import org.joda.time.DateTime;import com.travelzen.framework.net.http.TZHttpClient;import com.travelzen.tops.front.ota.member.item.CustomerItem;public class CSV { private OutputStream stream; private Map<String,String> fields; private static Map<String, Field> fieldMap = new HashMap<>(); public CSV(HttpServletResponse response,Map<String,String> fields,String fileName,Class<?> clz) throws IOException{ if(response == null || fields == null || fileName == null || clz == null) throw new IllegalArgumentException(); getFieldMap(clz,fieldMap); this.stream = response.getOutputStream(); this.fields = fields; response.setContentType("application/octet-stream;charset=GBK"); response.setHeader("Content-Disposition", "attachment;fileName="+ fileName); //写表头,生成指定名字的文件,返回客户端 StringBuilder hb = new StringBuilder(); for(Entry<String, String> e : fields.entrySet()) hb.append(e.getValue()+","); stream.write(hb.substring(0, hb.length() - 1).getBytes("GBK")); stream.flush(); } public void write(List<Object> data) throws IllegalArgumentException, IllegalAccessException, IOException{ for(Object o : data){ StringBuilder sb = new StringBuilder(); sb.append("\n"); for(String field : fields.keySet()){ Field f = fieldMap.get(field); f.setAccessible(true); Object value = f.get(o); if(value == null || StringUtils.isBlank(value.toString())){ sb.append(" ,"); } else if (f.getType() == Date.class) { sb.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value) + ","); } else if (f.getType() == DateTime.class) { sb.append(((DateTime)value).toString("yyyy-MM-dd HH:mm:ss") + ","); } else { String tmp = value.toString(); if(tmp.contains(",")) tmp = tmp.replace(",", "\",\""); sb.append(value.toString() + ","); } } stream.write(sb.substring(0, sb.length() - 1).getBytes("GBK")); stream.flush(); } } public void close() throws IOException{ stream.close(); } private static <T extends Object> void getFieldMap(Class<T> clz, Map<String, Field> result) { for (Field field : clz.getDeclaredFields()) { result.put(field.getName(), field); } if (clz.getSuperclass() != null) { getFieldMap(clz.getSuperclass(), result); } }}
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
软考中级精品资料免费领
- 历年真题答案解析
- 备考技巧名师总结
- 高频考点精准押题
- 资料下载
- 历年真题
193.9 KB下载数265
191.63 KB下载数245
143.91 KB下载数1148
183.71 KB下载数642
644.84 KB下载数2756
相关文章
发现更多好内容猜你喜欢
AI推送时光机 咦!没有更多了?去看看其它编程学习网 内容吧