com.niles.excel2json.objects.ExcelFile.java Source code

Java tutorial

Introduction

Here is the source code for com.niles.excel2json.objects.ExcelFile.java

Source

/*
 * Excel2JSON
 * 
 * Copyright (c) 2015 Niles Madison
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.niles.excel2json.objects;

import com.niles.excel2json.constants.StringConstants;
import com.niles.excel2json.tools.SystemTools;
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 org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

public class ExcelFile {

    private final static Logger logger = LoggerFactory.getLogger(ExcelFile.class.getName());

    String path;
    String fileName;
    String folderPath;
    String sheetName;

    public ExcelFile(String path) {
        this.path = path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public void process() throws Exception {
        File excel = new File(path);
        FileInputStream fis = SystemTools.getFileInputStream(excel);

        XSSFWorkbook wb = null;

        try {
            wb = new XSSFWorkbook(fis);
        } catch (IOException ex) {
            logger.error("Unable to process file [{}]\r\n{}", path, ex.getMessage());
            return;
        }

        this.fileName = excel.getName().replace(StringConstants.XLSX, "");
        this.folderPath = fileName + " Files";

        folderPath = SystemTools.createFolder(folderPath);

        int sheetCount = wb.getNumberOfSheets();

        int currentSheetNumber = 0;
        int rowCount = 0;
        int columnCount = 0;

        HashMap<Integer, String> headers = new HashMap<Integer, String>();

        /*
         * Itterate through the Excel sheets here and convert them to JSON
         */
        while (currentSheetNumber < sheetCount) {
            XSSFSheet current = wb.getSheetAt(currentSheetNumber);
            sheetName = current.getSheetName();

            // System.out.println(sheetName);
            if (current.getRow(0) == null) {
                // logger.error("[{}] Sheet contains no data", sheetName);
            } else {
                //logger.info("[{}] Processing sheet", sheetName);
                rowCount = current.getLastRowNum() + 1;
                columnCount = current.getRow(0).getPhysicalNumberOfCells();

                // System.out.println("Col Count: " + columnCount);
                // System.out.println("Row Count: " + rowCount);
                JSONArray myJSONArray = new JSONArray();
                JSONObject currentJSONObject = null;
                for (int a = 0; a < rowCount; a++) {
                    XSSFRow currentRow = current.getRow(a);

                    if (a == 0) {
                        logger.info("[{}] Loading header information", sheetName);
                        for (int currentCellNumber = 0; currentCellNumber < columnCount; currentCellNumber++) {
                            XSSFCell currentCell = currentRow.getCell(currentCellNumber);

                            String header = "Header" + currentCellNumber;

                            if (currentCell != null) {
                                if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                                    header = currentCell.getStringCellValue();
                                }

                                if (currentCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
                                    header = currentCell.getNumericCellValue() + "";
                                }
                            }

                            headers.put(currentCellNumber, header.replaceAll(" ", ""));
                        }
                    } else {
                        currentJSONObject = new JSONObject();

                        for (int currentCellNumber = 0; currentCellNumber < columnCount; currentCellNumber++) {
                            XSSFCell currentCell = currentRow.getCell(currentCellNumber);

                            String value = "";

                            if (currentCell != null) {
                                if (currentCell.getCellType() != XSSFCell.CELL_TYPE_ERROR
                                        && currentCell.getCellType() != XSSFCell.CELL_TYPE_FORMULA) {
                                    if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
                                        value = currentCell.getStringCellValue();
                                    }
                                    if (currentCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
                                        value = currentCell.getNumericCellValue() + "";
                                    }
                                    if (currentCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
                                        value = currentCell.getBooleanCellValue() + "";
                                    }

                                    if (value == null) {
                                        value = "";
                                    }
                                }
                            }

                            currentJSONObject.put(headers.get(currentCellNumber), value);
                        }
                        myJSONArray.add(currentJSONObject);
                    }
                }
                writeToJson(myJSONArray);
            }
            currentSheetNumber++;
        }
    }

    public void writeToJson(JSONArray myJSONArray) {
        String jsFilePath = folderPath + sheetName.replaceAll(" ", "") + ".js";
        String jsonFilePath = folderPath + sheetName.replaceAll(" ", "") + ".json";

        logger.info("Writing file {}", jsFilePath);

        try {
            // Create file
            FileWriter JSONFileStream = SystemTools.getFileWriter(jsFilePath);
            JSONFileStream.write("var " + sheetName.replaceAll("-", "").replaceAll(" ", "") + " = "
                    + myJSONArray.toJSONString() + ";");
            // JSONFileStream.write(myJSONArray.toJSONString());
            JSONFileStream.flush();
            JSONFileStream.close();
        } catch (IOException ex) {
            logger.error("[{}]  Error writing JSON\r\n{}", jsFilePath, ex.getMessage());
        }

        logger.info("Writing file {}", jsonFilePath);

        try {
            // Create file
            FileWriter JSONFileStream = SystemTools.getFileWriter(jsonFilePath);
            JSONFileStream.write(myJSONArray.toJSONString());
            // JSONFileStream.write(myJSONArray.toJSONString());
            JSONFileStream.flush();
            JSONFileStream.close();
        } catch (IOException ex) {
            logger.error("[{}]  Error writing JSON\r\n{}", jsonFilePath, ex.getMessage());
        }
    }
}