基于Java实现Json文件转换为Excel文件

作者:菜鸟小于 时间:2022-08-04 23:53:15 

一. 思路

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

标签:Java,Json,Excel
0
投稿

猜你喜欢

  • Java 实现判定顺序表中是否包含某个元素(思路详解)

    2023-09-11 01:03:04
  • C# InitializeComponent()方法案例详解

    2022-06-12 03:07:06
  • Java内存模型JMM与volatile

    2022-03-25 09:33:50
  • Java对象级别与类级别的同步锁synchronized语法示例

    2023-06-25 09:11:22
  • IDEA远程连接HBase及其Java API实战详解

    2023-11-27 21:54:46
  • 深入分析JAVA 建造者模式

    2023-03-14 01:32:27
  • 解决nacos升级spring cloud 2020.0无法使用bootstrap.yml的问题

    2021-12-02 19:44:29
  • Java适配器模式_动力节点Java学院整理

    2021-09-06 10:50:53
  • RocketMQ-延迟消息的处理流程介绍

    2023-07-28 01:58:59
  • 详解Java实现LRU缓存

    2023-06-05 19:24:08
  • SpringBoot深入分析讲解监听器模式上

    2022-06-25 21:04:04
  • Java原生服务器接收上传文件 不使用MultipartFile类

    2023-11-09 19:31:36
  • java类中生成jfreechart,返回图表的url地址 代码分享

    2023-09-08 00:54:07
  • 使用Spring组合自定义的注释 mscharhag操作

    2023-02-14 11:18:01
  • SpringBoot分离打Jar包的两种配置方式

    2023-01-30 09:06:59
  • C#实现观察者模式(Observer Pattern)的两种方式

    2023-06-20 21:05:18
  • Java并发编程之原子性-Atomic的使用

    2023-11-09 22:34:58
  • Spring Boot从Controller层进行单元测试的实现

    2023-07-21 03:07:10
  • springboot项目启动的时候参数无效的解决

    2022-09-03 14:50:29
  • 详解Spring Bean的集合注入和自动装配

    2023-02-18 15:02:58
  • asp之家 软件编程 m.aspxhome.com