1. 程式人生 > >JSON轉EXCEL程式碼( java)

JSON轉EXCEL程式碼( java)

依賴

   <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>fastjson</artifactId>
       <version>1.2.37</version>
   </dependency>
   <dependency>
       <groupId>org.apache.poi</groupId>
       <artifactId>poi</artifactId>
       <version>3.14</version>
   </dependency>
   <dependency>
       <groupId>org.apache.poi</groupId>
       <artifactId>poi-ooxml</artifactId>
       <version>3.14</version>
   </dependency>

程式碼

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.util.Set;

public class JSONToExcel {
    public static void main(String[] args) throws IOException {
        Set<String> keys = null;
        // 建立HSSFWorkbook物件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 建立HSSFSheet物件
        HSSFSheet sheet = wb.createSheet("sheet0");

        FileReader reader = new FileReader("c://resource.txt");
        BufferedReader br = new BufferedReader(reader);
        String str = null;
        int roleNo = 0;
        int rowNo = 0;
        while ((str = br.readLine()) != null) {
            JSONObject jsonObject = JSONObject.parseObject(str);
            // 建立HSSFRow物件
            HSSFRow row = sheet.createRow(roleNo++);
            // 建立HSSFCell物件
            if (keys == null) {
                //標題
                keys = jsonObject.keySet();
                for (String s : keys) {
                    HSSFCell cell = row.createCell(rowNo++);
                    cell.setCellValue(s);
                }
                rowNo = 0;
                row = sheet.createRow(roleNo++);
            }

            for (String s : keys) {
                HSSFCell cell = row.createCell(rowNo++);
                cell.setCellValue(jsonObject.getString(s));
            }
            rowNo = 0;
            System.out.println(rowNo);

        }

        br.close();
        reader.close();

        // 輸出Excel檔案
        FileOutputStream output = new FileOutputStream("c://target.xls");
        wb.write(output);
        wb.close();
        output.flush();
        output.close();
    }
}