/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package asistencia.utilities;

import java.io.IOException;
import java.io.OutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

/**
 *
 * @author sistem19user
 */
public class ExcelHelper {

    private String[] headers;
    private Object[][] data;
    private OutputStream output;
    private String sheetName;

    public ExcelHelper(OutputStream output) {
        this.output = output;
    }

    public void setHeaders(String[] headers) {
        this.headers = headers;
    }

    public void setSheetName(String sheetName) {
        this.sheetName = sheetName;
    }
    
    public void setData(Object[][] data){
        this.data = data;
    }
    
    public void generate() throws IOException {
        Workbook workbook = new HSSFWorkbook();
        //Crea hoja nueva
        Sheet sheet = workbook.createSheet(sheetName);

        CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
        headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

        Row headerRow = sheet.createRow(0);


        int i = 0;
        for (String header : headers) {
            Cell cell = headerRow.createCell(i++);
            cell.setCellStyle(headerStyle);
            cell.setCellValue(header);
        }

        i = 1;
        Row row;
        for (Object[] array : data) {
            row = sheet.createRow(i++);

            Cell cell;
            int j = 0;
            for (Object value : array) {
                cell = row.createCell(j++);

                if (value instanceof Integer) {
                    cell.setCellValue(Integer.parseInt(value.toString()));
                } else if (value instanceof String) {
                    cell.setCellValue(value.toString());
                } else if (value instanceof Double) {
                    cell.setCellValue(Double.parseDouble(value.toString()));
                } else if (value instanceof Boolean) {
                    cell.setCellValue((boolean) value);
                } else {
                    cell.setCellValue(value.toString());
                }
            }
        }

        sheet.createFreezePane(0, 1);
        workbook.write(output);
    }

}