一. 思路

今天接到个小任务,让把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;
}
}
}

Json文件转换为Excel文件!涉及读文件,时间戳转化,写文档的更多相关文章

  1. PyQt5UI文件转换为对应版本的py文件

    PyQt5 UI文件转换为对应版本的py文件 #coding=utf-8 ''' PyQt5 UI文件转换为对应版本的py文件 python -m PyQt5.uic.pyuic untitled.u ...

  2. sql文件转换为excel文件

    最近经常需要把sql整理成excel,本人比较懒,所以写一个小工具,用到了jxl包.以前没有接触过,正好了解一下. 一.基础知识       jxl操作excel包括对象 Workbook,Sheet ...

  3. python (11)文件的读写 按行读文件

    读文件: 读取文件 f = open('\info.txt') fil = f.read() f.close() 按行读文件: f = open("info.txt") while ...

  4. 【.NET深呼吸】Zip文件操作(1):创建和读取zip文档

    .net的IO操作支持对zip文件的创建.读写和更新.使用起来也比较简单,.net的一向作风,东西都准备好了,至于如何使用,请看着办. 要对zip文件进行操作,主要用到以下三个类: 1.ZipFile ...

  5. 根据传入的文件名称动态从moglifs图片服务器拿到pdf文档并在线浏览

    1.通过百度编辑器上传pdf文档等附件时,在上传方法中将返回的url进行设定,以达到后期点击后可进行浏览的效果: public static final State save(HttpServletR ...

  6. excel保存时出现“请注意,您的文档的部分内容可能包含了文档检查器无法删除的个人信息”

    这个问题的原因是由于工作簿包含宏.ActiveX控件等内容, 而Excel被设置为在保存文件时自动删除文件属性中的个人信息,因而出现该对话框.如果要避免出现这个提示,可进行如下设置: Excel 20 ...

  7. android 开发 获取各种intent (图片、apk文件、excel、pdf等文件)

    public static Intent openFile(String filePath){ File file = new File(filePath); if(!file.exists()) r ...

  8. DWG2SHP DXF2SHP 如何把AutoCAD的DWG,DXF文件转换为Esri ArcGIS的Shape文件

    dwg是AutoCAD创立的一种图纸保存格式,已经成为二维CAD的标准格式,很多其他CAD为了兼容AutoCAD,也直接使用dwg作为默认工作文件. 地图shape文件由ESRI开发,一个ESRI的s ...

  9. hive分区与实际分区文件不匹配导致spark读文件出错的问题解决

    先解释下,由于历史原因导致hive中的看到分区比hdfs中的文件夹不匹配,存在hive中分区数有,实际hdfs中无此文件夹. spark中通过sparkSQL读取hive中的该表时,将会出现异常. 解 ...

随机推荐

  1. tomcat部署项目问题

    tomcat部署项目的时候,报内存溢出,一种解决方案是直接添加内存,网上都有教程,如下: Windows下,在文件/bin/catalina.bat,Linux下,在文件/bin/catalina.s ...

  2. PHP中间件

    定义 首先什么是php的中间件? 根据zend-framework中的定义: 所谓中间件是指提供在请求和响应之间的,能够截获请求,并在其基础上进行逻辑处理,与此同时能够完成请求的响应或传递到下一个中间 ...

  3. 实现 Abp Vnext Pro

    Abp Vnext Pro 的 Vue 实现版本 开箱即用的中后台前端/设计解决方案 知识点 .Net Core5.0 Abp Vnext 4.x , Ant Design, Vue2.x Mysql ...

  4. 剑指 Offer 13. 机器人的运动范围 + 深搜 + 递归

    剑指 Offer 13. 机器人的运动范围 题目链接 package com.walegarrett.offer; /** * @Author WaleGarrett * @Date 2020/12/ ...

  5. 【ZeyFraのJavaEE开发小知识03】@DateTimeFomat和@JsonFormat

    关于在Element UI的el-dialog组件中使用echarts的问题 问题描述: "Cannot read property 'getAttribute' of null" ...

  6. 微软跨平台UI框架MAUI真的要来啦

    .NET 6 preview已经上线,是时候为在BUILD 2020上宣布的新.NET Multi-platform App UI(MAUI)做准备了.对于客户端应用程序开发人员来说,这一年.NET有 ...

  7. 【codeforces - 1307G】Cow and Exercise

    目录 description solution accepted code details description 给定 n 点 m 边简单有向图,有边权. q 次询问,每次给出 xi.可以增加某些边 ...

  8. Qt 自定义 进度条 纯代码

    一 结果图示 二 代码 头文件 #ifndef CPROGRESS_H #define CPROGRESS_H #include <QWidget> #include <QPaint ...

  9. Poj 3370

    题目传送门:https://vjudge.net/problem/POJ-3370 题意:在n个数中找K个数使得他们的和为c的倍数. 题解:抽屉原理,同poj 2356 只不过写法上有所简化. 简化版 ...

  10. 操作系统实验(一)-Shell编程

    操作系统实验:Shell编程 emmmmm,实验前老师发了一份实验说明,里面有教怎么配置虚拟机Ubuntu.这里就不做过多叙述,需要说明的是,kali和ubuntu都可以以shell运行这个C语言程序 ...