在报表项目开发过程中,UI端显示的数据用户想通过界面的”下载“按钮保存下来,而数据已经以JSON格式得到了,这是只需要把json格式的文件转化为excel,怎么转化,开源的有org.json.CDL,但这个东东的缺点是转化后就不能UI上的顺序保持一致,为此专门改写了网上的代码,见

  List exportData = getKeyValFromJson(account_rep);
  LinkedHashMap map = getKeyFromJson(account_rep);

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.beanutils.BeanUtils;
 
/**
 * 文件操作
 */
public class CSVUtils {
 
  /**
   * 生成为CVS文件 
   * @param exportData
   *       源数据List
   * @param map
   *       csv文件的列表头map
   * @param outPutPath
   *       文件路径
   * @param fileName
   *       文件名称
   * @return
   */
  @SuppressWarnings("rawtypes")
  public static File createCSVFile(List exportData, LinkedHashMap map, String outPutPath,
                   String fileName,String encoding) {
    File csvFile = null;
    BufferedWriter csvFileOutputStream = null;
    try {
      File file = new File(outPutPath);
      if (!file.exists()) {
        file.mkdir();
      }
      //定义文件名格式并创建
      csvFile = File.createTempFile(fileName, ".csv", new File(outPutPath));
      System.out.println("csvFile:" + csvFile);
      // UTF-8使正确读取分隔符"," 
      csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
        csvFile), encoding), 1024);
      System.out.println("csvFileOutputStream:" + csvFileOutputStream);
      // 写入文件头部 
      for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();) {
        java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
        csvFileOutputStream
          .write((String) propertyEntry.getValue() != null ? (String) propertyEntry
            .getValue() : "");
        if (propertyIterator.hasNext()) {
          csvFileOutputStream.write(",");
        }
      }
      csvFileOutputStream.newLine();
      // 写入文件内容 
      for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
        Object row = (Object) iterator.next();
        for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator
          .hasNext();) {
          java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
            .next();
          csvFileOutputStream.write((String) BeanUtils.getProperty(row,
            (String) propertyEntry.getKey()));
          if (propertyIterator.hasNext()) {
            csvFileOutputStream.write(",");
          }
        }
        if (iterator.hasNext()) {
          csvFileOutputStream.newLine();
        }
      }
      csvFileOutputStream.flush();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        csvFileOutputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return csvFile;
  }
 
  /**
   * 下载文件
   * @param response
   * @param csvFilePath
   *       文件路径
   * @param fileName
   *       文件名称
   * @throws IOException
   */
  public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName)
                                                  throws IOException {
    response.setContentType("application/csv;charset=UTF-8");
    response.setHeader("Content-Disposition",
      "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
 
    InputStream in = null;
    try {
      in = new FileInputStream(csvFilePath);
      int len = 0;
      byte[] buffer = new byte[1024];
      response.setCharacterEncoding("UTF-8");
      OutputStream out = response.getOutputStream();
      while ((len = in.read(buffer)) > 0) {
        out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
        out.write(buffer, 0, len);
      }
    } catch (FileNotFoundException e) {
      System.out.println(e);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    }
  }
 
  
 
  /**
   * 下载文件
   * @param response
   * @param csvFilePath
   *       文件路径
   * @param fileName
   *       文件名称
   * @throws IOException
   */
  public static void get(HttpServletResponse response, String csvFilePath, String fileName)
                                                  throws IOException {
    response.setContentType("application/csv;charset=UTF-8");
    response.setHeader("Content-Disposition",
      "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
 
    InputStream in = null;
    try {
      in = new FileInputStream(csvFilePath);
      int len = 0;
      byte[] buffer = new byte[1024];
      response.setCharacterEncoding("UTF-8");
      OutputStream out = response.getOutputStream();
      while ((len = in.read(buffer)) > 0) {
        out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
        out.write(buffer, 0, len);
      }
    } catch (FileNotFoundException e) {
      System.out.println(e);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    }
  }
  
  /**
   * 删除该目录filePath下的所有文件
   * @param filePath
   *      文件目录路径
   */
  public static void deleteFiles(String filePath) {
    File file = new File(filePath);
    if (file.exists()) {
      File[] files = file.listFiles();
      for (int i = 0; i < files.length; i++) {
        if (files[i].isFile()) {
          files[i].delete();
        }
      }
    }
  }
 
  /**
   * 删除单个文件
   * @param filePath
   *     文件目录路径
   * @param fileName
   *     文件名称
   */
  public static void deleteFile(String filePath, String fileName) {
    File file = new File(filePath);
    if (file.exists()) {
      File[] files = file.listFiles();
      for (int i = 0; i < files.length; i++) {
        if (files[i].isFile()) {
          if (files[i].getName().equals(fileName)) {
            files[i].delete();
            return;
          }
        }
      }
    }
  }
 
  /**i
   * 返回数组里面存放的是每条item的key-value
   * @param sjoin
   */ 
  public static List getKeyValFromJson(String json){
	  if(json==null || "".endsWith(json)){return null;}
	  List exportData = new ArrayList<Map>();
	 
	  int lenOfJson = json.length();
	  int itemEndIndex = 0;
	  String item="";
	  //[{"date":"2016-08-24","campaign":"铁弯头 额外","group_name":"cese"}]
	  for(int index= 0; index < lenOfJson; index++){
		  if(json.charAt(index)=='[') {
			  System.out.println("开始解析JSON");
		  }
		  
		  if(json.charAt(index)=='{') {//unitl next item
			  System.out.println("开始解析一条item");
			  Map row = new LinkedHashMap<String, String>();
			  index++;
			  while(json.charAt(index)!='}'){
				  index=json.indexOf("\"",index);//direct into '"'
				  int index_keyend=json.indexOf("\":\"",index);//get key的endIndex(不计)
				  String key = json.substring(index+1,index_keyend);
				  
				  index = json.indexOf("\"",index_keyend+3);// index
				  String value = json.substring(index_keyend+3, index);
				  
				  value.replaceAll(",", "");
				  System.out.println(key+":"+value);
				  row.put(key, value);
				  //"," OR "}" after value
				  index+=1;
				  if(json.charAt(index)=='}'){
					  break;
				  }
			  }
			  System.out.println("结束解析一条item");
			  exportData.add(row);
		  }
			  
			  
		 if(json.charAt(index)==']') {
			 System.out.println("结束解析JSON");
	     }  
	  }
	      
	  return exportData;
  }
  
  /**i
   * 返回数组里面存放的是每条item的key-key
   * @param sjoin
   */ 
  public static LinkedHashMap getKeyFromJson(String json){
	  if(json==null || "".endsWith(json)){return null;}
	  LinkedHashMap row = new LinkedHashMap<String, String>();
	  int lenOfJson = json.length();
	  String item="";
	//[{"date":"2016-08-24","campaign":"铁弯头 额外","group_name":"cese"}]
	  for(int index= 0; index < lenOfJson; index++){
		  if(json.charAt(index)=='[') {
			  System.out.println("开始解析JSON");
		  }
		  
		  if(json.charAt(index)=='{') {//unitl next item
			  System.out.println("开始解析一条item");
			  index++;
			  while(json.charAt(index)!='}'){
				  index=json.indexOf("\"",index);//direct into '"'
				  int index_keyend=json.indexOf("\":\"",index);//get key的endIndex(不计)
				  String key = json.substring(index+1,index_keyend);
				  
				  index = json.indexOf("\"",index_keyend+3);// index
				  String value = json.substring(index_keyend+3, index);
				  
				  value =value.replaceAll(",", "");
				  System.out.println(key+":"+value);
				  row.put(key, key);
				  
				  //"," OR "}" after value
				  index+=1;
				  if(json.charAt(index)=='}'){
					  break;
				  }
			  }
			  
			  System.out.println("结束解析一条item");
		  }
		if(row.size()>0){
			break;
		} 

	  }
	  return row;
  }
  /**
   * 测试数据
   * @param args
   */
  @SuppressWarnings({ "rawtypes", "unchecked" })
  public static void main(String[] args) {
  String account_rep = "";
  List exportData = getKeyValFromJson(account_rep);
  LinkedHashMap map = getKeyFromJson(account_rep);
    /*List exportData = new ArrayList<Map>();
    Map row1 = new LinkedHashMap<String, String>();
    row1.put("1", "11");
    row1.put("2", "12");
    row1.put("3", "13");
    row1.put("4", "14");
    exportData.add(row1);
    row1 = new LinkedHashMap<String, String>();
    row1.put("1", "21");
    row1.put("2", "22");
    row1.put("3", "23");
    row1.put("4", "24");
    exportData.add(row1);
    LinkedHashMap map = new LinkedHashMap();
    map.put("1", "first");
    map.put("2", "second");
    map.put("3", "third");
    map.put("4", "fourth");*/
 
    String path = "c:/export/";
    String fileName = "文件导出";
    File file = CSVUtils.createCSVFile(exportData, map, path, fileName,"GB18030");
    String fileName2 = file.getName();
    System.out.println("文件名称:" + fileName2);
  }
}


GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 4 个月前
8c391e04 6 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐