JsonArry转换为CSV,Excel可读

来源:互联网 发布:淘宝权又在斗鱼直播 编辑:程序博客网 时间:2024/05/16 05:05
<span style="font-family: Simsun; background-color: rgb(255, 255, 255);">又是一天,最近成都有点冷啊,难道是自己的身体变虚了,哎哟·····</span>
    正文:项目要求把数据库中的一些数据导出成Excel可读的格式,由于一些数据涉及到联查以及隐私性的问题,不能够直接从数据库表中直接导出,我的做法是先把数据库中的数据查出,然后转换成JsonArray格式,然后remove一些隐私信息,最后再把JsonArray格式导出成Excel可读格式。需要解决的就是如何把JsonArray转换成Excel可读格式。
    一开始差点走入误区!准备调用DLL了~Google一下,JsonArray最方便的是转换为CSV格式,CSV格式的文件实测可以用excel打开。在Github上看到一个JsonArray2CSV的开源项目,结果别个用的是Node.js。我感觉CSV格式就是逗号分隔的纯字符串,有种自己写一个函数的冲动了,忍了忍还是抑制住了(其实就是懒害羞)。
    遇到这种问题还是得靠老美!在StackOverFlow上找到相似问题:http://stackoverflow.com/questions/7172158/converting-json-to-xls-csv-in-java,其中置顶的回答完美解决了问题。老美用到了org.json包,这和我之前用的net.sf.json工具包中有重叠,比如JsonArray,因为最开始我用的是net.sf.json工具包来实现从数据库中读出list,然后转换成JSONARRAY。取了个巧,两个JSONARRAY互相转换了下最终效果贴一下代码:

package com.eip.util;import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.json.CDL;import org.json.JSONException;import net.sf.json.JSONArray;/** * @author Fly_Bear * DESC: 通过org.json包来实现jsonarray转换成CSV字符串 */public class Json2csvUtil { private JSONArray jsonArray; /**  * @param jsonArray 传入一个net.sf.json.JSONArry数组  */ public Json2csvUtil(JSONArray jsonArray) {  // TODO Auto-generated constructor stub  this.jsonArray = jsonArray; }  /**  * @param jsonArray the jsonArray to set  */ public void setJsonArray(JSONArray jsonArray) {  this.jsonArray = jsonArray; }  /**  * @return the jsonArray  */ public JSONArray getJsonArray() {  return jsonArray; }  /**  * @author Fly_Bear  * @return 返回一个满足CSV格式的字符串  * @throws JSONException  *    */ /**  *  * @return 返回csv格式的字符串  * @throws JSONException  */ public String getCSVString() throws JSONException{  //将jsonArray转换成纯字符串(涵盖所有符号)  String jsonString = jsonArray.toString();  //利用字符串生成org.json.JSONArray,实现net.sf.json.jsonArray与org.json.JSONArray转换     org.json.JSONArray orgjsonarray = new org.json.JSONArray(jsonString);     //利用org.json工具类生成CSV格式要求的String。    csv =CDL.toString(orgjsonarray);     return csv; }}


最后将生成的CSV格式的String字符串输入到File即可

File file=new File("yourpath/fromJSON.csv");     String csv = CDL.toString(docs);     FileUtils.writeStringToFile(file, csv);



0 1
原创粉丝点击