82 lines
2.7 KiB
Java
82 lines
2.7 KiB
Java
package com.example.sso.controller;
|
|
import com.alibaba.fastjson.JSONArray;
|
|
import com.alibaba.fastjson.JSONObject;
|
|
import com.example.sso.dao.Now;
|
|
import com.example.sso.dao.Query;
|
|
import org.apache.poi.ss.usermodel.*;
|
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
|
|
|
|
|
import java.io.FileInputStream;
|
|
import java.io.FileOutputStream;
|
|
import java.io.IOException;
|
|
public class NowDta {
|
|
public static void main(String[] args) {
|
|
JSONArray jsonArray = Query.car();
|
|
|
|
|
|
// 将JSONArray数据追加到现有的Excel文件
|
|
appendToExcel(jsonArray, "C:\\Users\\李嘉卓\\Desktop\\data.xlsx", "Sheet1");
|
|
|
|
for (Object o : jsonArray){
|
|
JSONObject te = (JSONObject) o;
|
|
String id = te.getString("_id");
|
|
String id1 = Now.id(id);
|
|
System.out.println(id1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
public static void appendToExcel(JSONArray jsonArray, String excelFilePath, String sheetName) {
|
|
Workbook workbook = null;
|
|
try (FileInputStream fileIn = new FileInputStream(excelFilePath)) {
|
|
// 读取现有的工作簿
|
|
workbook = new XSSFWorkbook(fileIn);
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
|
|
if (workbook == null) {
|
|
System.out.println("无法读取现有的Excel文件");
|
|
return;
|
|
}
|
|
|
|
// 获取或创建工作表
|
|
Sheet sheet = workbook.getSheet(sheetName);
|
|
if (sheet == null) {
|
|
sheet = workbook.createSheet(sheetName);
|
|
// 创建标题行
|
|
Row headerRow = sheet.createRow(0);
|
|
headerRow.createCell(0).setCellValue("jsd");
|
|
headerRow.createCell(1).setCellValue("dsfs");
|
|
headerRow.createCell(2).setCellValue("asfda");
|
|
}
|
|
|
|
// 获取最后一行的行号
|
|
int lastRowNum = sheet.getLastRowNum();
|
|
|
|
// 写入数据行
|
|
for (int i = 0; i < jsonArray.size(); i++) {
|
|
JSONObject jsonObject = jsonArray.getJSONObject(i);
|
|
Row row = sheet.createRow(lastRowNum + 1 + i);
|
|
row.createCell(0).setCellValue(jsonObject.getString("is"));
|
|
row.createCell(1).setCellValue(jsonObject.getString("jg"));
|
|
row.createCell(2).setCellValue(jsonObject.getString("hphm"));
|
|
}
|
|
|
|
// 自动调整列宽
|
|
for (int i = 0; i < 3; i++) {
|
|
sheet.autoSizeColumn(i);
|
|
}
|
|
|
|
// 将工作簿写回文件
|
|
try (FileOutputStream fileOut = new FileOutputStream(excelFilePath)) {
|
|
workbook.write(fileOut);
|
|
System.out.println("Excel文件已成功更新: " + excelFilePath);
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}
|