基于Java实现Json文件转换为Excel文件
作者:菜鸟小于 发布时间:2022-08-04 23:53:15
标签:Java,Json,Excel
一. 思路
今天接到个小任务,让把json文件转换成excel文件,按照列展开.
思路:既然json已经都已经是现成的,那直接将json文件做读操作,在通过不同的key,找到对应的信息,在存到单元格中,在写操作,生成excel文档
二.jar包
涉及到的jar包,阿里的fastjson和poi的jar包
三.代码
我的json文档里数据的格式是这样的
[
{
"total": 1,
"name": "规则限制:XXXX",
"timeStr": 1619242800000,
"message": "XXX",
"hehe": ""
},
{
"total": 2,
"name": "服务异常:XXXX",
"timeStr": 1619240400000,
"message": "XXX!",
"hehe": ""
}
]
1.先对json文件进行读操作,提取String对象,在将String对象转换为JsonArray
public static String readJsonFile(String path) {
String jsonString = "";
try {
File file = new File(path);
FileReader fileReader = new FileReader(file);
Reader reader = new InputStreamReader(new FileInputStream(file),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonString = sb.toString();
return jsonString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
我试过直接读文件,出现中文乱码,所以记得用UTF-8编码,否则会是乱码
2.文件内容以String的形式获取到,这时创建excel文件,在将String转换为jsonArray形式遍历,分别插入到excel文件的单元格cell中,在做写操作
public static void main(String[] args) {
String json = ToJson.readJsonFile("C:\\Users\\yu\\Desktop\\new.json");
//System.out.println(json);
//JSONObject object = JSON.parseObject(json);
try {
//生成excel文件存放的地址
String uploadFile = "D:/test.xlsx";
OutputStream excel = new FileOutputStream(uploadFile);
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet();
XSSFRow row = null;//行
XSSFCell cell = null;//单元格
row = sheet.createRow(0);
//这是创建excel上边的标题头
String[] names = { "total", "异常", "页面名称", "信息","时间","工号"};
for (int index = 0; index < 5; index++) {
cell = row.createCell(index);
cell.setCellValue(names[index]);
}
int count = 1;
JSONArray dataArray = JSONArray.parseArray(json);
for(int i = 0; i < dataArray.size();i++){
JSONObject dataObj = dataArray.getJSONObject(i);
//获取不同key中的值
String total = dataObj.getString("total");
String name = dataObj.getString("name");
String[] nameArray = name.split(":");//这个是通过分号获得两个值,分别写在excel中
String name1 = nameArray[0];
String name2 = nameArray[1];
String timeStr = dataObj.getString("timeStr");
String time = ToJson.stampToTime(timeStr);//这个根据时间戳转换为正常年月日,时分秒
String message = dataObj.getString("message");
String staffId = dataObj.getString("hehe");
row = sheet.createRow(count);
cell = row.createCell(0);
cell.setCellValue(total);
cell = row.createCell(1);
cell.setCellValue(name1);
cell = row.createCell(2);
cell.setCellValue(name2);
cell = row.createCell(3);
cell.setCellValue(message);
cell = row.createCell(4);
cell.setCellValue(time);
cell = row.createCell(5);
cell.setCellValue(staffId);
count++;
}
workBook.write(excel);
} catch (Exception e) {
e.printStackTrace();
}
}
时间戳的转换方法:
public static String stampToTime(String stamp) {
String sd = "";
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sd = sdf.format(new Date(Long.parseLong(stamp))); // 时间戳转换日期
return sd;
}
运行即可获得excel文件
全部代码:
package com.china.excelToJson;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ToJson {
public static void main(String[] args) {
String json = ToJson.readJsonFile("C:\\Users\\yu\\Desktop\\new.json");
//System.out.println(json);
//JSONObject object = JSON.parseObject(json);
try {
//生成excel文件存放的地址
String uploadFile = "D:/test.xlsx";
OutputStream excel = new FileOutputStream(uploadFile);
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet();
XSSFRow row = null;//行
XSSFCell cell = null;//单元格
row = sheet.createRow(0);
//这是创建excel上边的标题头
String[] names = { "total", "异常", "页面名称", "信息","时间","工号"};
for (int index = 0; index < 5; index++) {
cell = row.createCell(index);
cell.setCellValue(names[index]);
}
int count = 1;
JSONArray dataArray = JSONArray.parseArray(json);
for(int i = 0; i < dataArray.size();i++){
JSONObject dataObj = dataArray.getJSONObject(i);
//获取不同key中的值
String total = dataObj.getString("total");
String name = dataObj.getString("name");
String[] nameArray = name.split(":");//这个是通过分号获得两个值,分别写在excel中
String name1 = nameArray[0];
String name2 = nameArray[1];
String timeStr = dataObj.getString("timeStr");
String time = ToJson.stampToTime(timeStr);//这个根据时间戳转换为正常年月日,时分秒
String message = dataObj.getString("message");
String staffId = dataObj.getString("hehe");
row = sheet.createRow(count);
cell = row.createCell(0);
cell.setCellValue(total);
cell = row.createCell(1);
cell.setCellValue(name1);
cell = row.createCell(2);
cell.setCellValue(name2);
cell = row.createCell(3);
cell.setCellValue(message);
cell = row.createCell(4);
cell.setCellValue(time);
cell = row.createCell(5);
cell.setCellValue(staffId);
count++;
}
workBook.write(excel);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String stampToTime(String stamp) {
String sd = "";
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sd = sdf.format(new Date(Long.parseLong(stamp))); // 时间戳转换日期
return sd;
}
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
来源:https://www.cnblogs.com/Young111/p/14702241.html


猜你喜欢
- 一般认为:foreach (object obj in checkedListBox1.SelectedItems)即可遍历选中的值。其实这
- 最近客户更新系统发现,以前的项目在调用相机的时候,闪退掉了,很奇怪,后来查阅后发现,Android 6.0以后需要程序授权相机权限,默认会给
- 程序员讨厌写文档, 讨厌写注释, 而我还讨厌写日志, 输出一个 "Id=5, 姓名=王大锤
- Android调试出现The selected device is incompatible问题解决在做Android调试时碰到该问题。详情
- 一、前言环境:jdk 1.8,SpringCloud Greenwich.SR2。如题,springcloud config-client启
- 背景:用习惯了idea再去用eclipse实在用的不习惯,于是将老的eclipse项目导入到eclipse,网上有很多教程,看了很多博客都不
- foreach查询不出结果也不报错问题首先,执行的时候语法没有报错,其次sql语句拿到数据库去执行能查到数据,但是在接口这边返回空输数据,查
- 确保这个修改是正确的(否则将会出现乱码)创建i18n文件夹(就是国际化的意思),然后在此文件加下创login.properties logi
- java中Path是什么?在计算机上安装Java后,需要设置PATH环境变量以便从任何目录方便地运行可执行文件(javac.exe,java
- 前言对于正则表达式,相信很多人都知道,但是很多人的第一感觉就是难学,因为看第一眼时,觉得完全没有规律可寻,而且全是一堆各种各样的特殊符号,完
- 1、检测权限因为dump系统lsass内存和sam注册表需要管理员权限,所以首先需要对当前进程上下文权限做判断。public static
- Java 中的内部类这是一个 Java 内部类的简单实现:public class OutterJava { pr
- 1. xml文件中加入自定义 搜索view<com.etoury.etoury.ui.view.IconCenterEditText
- 一、单线程扫描1.代码using System;using System.Windows.Forms;using System.Net;us
- 面向对象有封装、继承、多态这三个特性,面向对象编程按照现实世界的特点来管理复杂的事物,把它们抽象为对象,具有自己的状态和行为,通过对消息的反
- 本文实例为大家分享了Java实现猜拳游戏的具体代码,供大家参考,具体内容如下一、问题简介通过控制台方式实现一个人机对战的猜拳游戏,用户通过输
- 问:怎样才能将XML文件导入SQL Server 2000? 答:将XML文件导入SQL Server有若干种方法,这里提供其中的3种: 大
- 如下所示:if(File.Exists(path)){// 是文件}else if(Directory.Exists(path)){// 是
- 1. 概述本文主要包括以下几个方面:编码基本知识,Java,系统软件,url,工具软件等。在下面的描述中,将以"中文"两
- 介绍原型模式(Prototype Pattern):使用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。原型模式是一种对象创建