json to excel java_json文件转excel表格

今天从别的网站上搞了些数据,运营的要用,是json格式的,但是运营部要excel格式,所以就试着写了一个工具类,主要用到apache的POI:

package com.cnx.lbyc.util;

import java.io.*;

import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFRichTextString;

import org.apache.poi.hssf.usermodel.HSSFRow;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.json.JSONArray;

import org.json.JSONObject;

public class Json2Excel {

public Json2Excel() {

}

public static void build(OutputStream output, String json, String[] properties) {

build(output, json, properties, properties);

}

public static void build(OutputStream output, String json, String[] properties, String[] columnsNames) {

HSSFWorkbook libro = new HSSFWorkbook();

HSSFSheet hoja = libro.createSheet();

HSSFRow header = hoja.createRow(0);

JSONArray array = new JSONArray(json);

int e;

for(e = 0; e 

String object = columnsNames[e];

HSSFCell row = header.createCell(e);

HSSFRichTextString j = new HSSFRichTextString(object);

row.setCellValue(j);

}

for(e = 0; e 

JSONObject var16 = array.getJSONObject(e);

HSSFRow var17 = hoja.createRow(e + 1);

for(int var18 = 0; var18 

String string = properties[var18];

HSSFCell cell = var17.createCell(var18);

try {

HSSFRichTextString text = new HSSFRichTextString(var16.get(string).toString());

cell.setCellValue(text);

} catch (Exception var15) {

//                    var15.printStackTrace();

//                    HSSFRichTextString text = new HSSFRichTextString(var16.getDouble(string) + "");

//                    cell.setCellValue(text);

}

}

}

try {

libro.write(output);

} catch (Exception var15) {

var15.printStackTrace();

}

}

public static void main(String [] args){

try {

FileReader reader = new FileReader(new File("/Users/gefufeng/Downloads/document.json"));

BufferedReader bufferedReader = new BufferedReader(reader);

String line = null;

StringBuffer stringBuffer = new StringBuffer();

while ((line= bufferedReader.readLine()) != null){

stringBuffer.append(line);

}

FileOutputStream xlsStream = new FileOutputStream("/Users/gefufeng/work/json2excel/document.xls");

Json2Excel.build(xlsStream, stringBuffer.toString(), new String[]{"userGlobalId","companyName","address","longitude","latitude"});

xlsStream.close();

}catch (Exception e){

e.printStackTrace();

}

}

}

json文件格式如下:

[

{

"userGlobalId": "",

"companyName": "",

"address": "",

"longitude": 121.354376,

"latitude": 31.168106,

}

]

so easy.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值