package excel;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class excel {
public static void main(String[] args) throws IOException {
jsonToExcel("C://Users//xxx//Desktop//aa.json", "D://");
}
static void jsonToExcel(String readPath, String outputPath) throws IOException {
Set keys = null;
FileReader fileReader = new FileReader(readPath);
BufferedReader br = new BufferedReader(fileReader);
String str;
int roll = 0;
int cellNo = 0;
int count = 0;
int page = 50000;
int size = (int) br.lines().count();
fileReader = new FileReader(readPath);
br = new BufferedReader(fileReader);
List jsonObjectList = new ArrayList<>();
while ((str = br.readLine()) != null) {
count ++;
JSonObject jsonObject = JSONObject.parseObject(str);
jsonObjectList.add(jsonObject);
//每5万条输出一次
if ((count % page == 0 && count != 0 ) || count >= size) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet0");
HSSFRow row ;
//表头拼接
if (keys == null) {
keys = jsonObject.keySet();
row = sheet.createRow(roll);
for (String s : keys) {
HSSFCell cell = row.createCell(cellNo ++);
cell.setCellValue(s);
}
cellNo = 0;
roll ++;
}
//行数据生成
for (JSonObject object : jsonObjectList) {
row = sheet.createRow(roll);
for (String s : keys) {
HSSFCell cell = row.createCell(cellNo ++ );
cell.setCellValue(object.getString(s));
}
cellNo = 0;
roll ++;
}
//文件输出
FileOutputStream output = new FileOutputStream(outputPath + "target" + UUID.randomUUID() + ".xls");
wb.write(output);
wb.close();
output.flush();
output.close();
roll = 0;
keys = null;
jsonObjectList.clear();
}
}
br.close();
fileReader.close();
System.out.println("生成完毕");
}
}