file.save.spreadsheet.model.SaveXlsxFileModel.java Source code

Java tutorial

Introduction

Here is the source code for file.save.spreadsheet.model.SaveXlsxFileModel.java

Source

/*
CSVFileModel -- a class within the Machine Artificial Vision Network(Machine Artificial Vision Network)
Copyright (C) 2012, Kaleb Kircher.
    
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
    
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package file.save.spreadsheet.model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * An implementation of SaveMatrixFileModelInterface. SaveXlsxFileModel knows how to
 * parse two-dimensional Arrays of primitive doubles into external Microsoft .xlsx files.
 * @author Kaleb
 */
public class SaveXlsxFileModel implements SaveMatrixFileModelInterface {
    private double[][] matrix;

    /**
     * Set the path to the file that defines the new Model.
     * @param path to the file containing the model data
     */
    @Override
    public void setModel(String path, double[][] matrix) throws IOException, InvalidFormatException {
        this.matrix = matrix;

        Workbook wb = new XSSFWorkbook();

        Sheet sheet = wb.createSheet("Simulyn");

        for (int i = 0; i < this.matrix.length; i++) {
            sheet.createRow(i);
            for (int j = 0; j < this.matrix[i].length; j++) {
                sheet.getRow(i).createCell(j, Cell.CELL_TYPE_NUMERIC).setCellValue(this.matrix[i][j]);
            }
        }

        FileOutputStream outPutStream = null;
        try {
            outPutStream = new FileOutputStream(path);
            wb.write(outPutStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outPutStream != null) {
                try {
                    outPutStream.flush();
                    outPutStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}