Example usage for org.apache.poi.xssf.usermodel XSSFSheet createRow

List of usage examples for org.apache.poi.xssf.usermodel XSSFSheet createRow

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFSheet createRow.

Prototype

@Override
public XSSFRow createRow(int rownum) 

Source Link

Document

Create a new row within the sheet and return the high level representation Note: If a row already exists at this position, it is removed/overwritten and any existing cell is removed!

Usage

From source file:minor.dbook.java

private void writetoexcel() {
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet ws = wb.createSheet();

    //load data to treemap

    TreeMap<String, Object[]> data = new TreeMap<>();

    //add column headers

    data.put("-1", new Object[] { model.getColumnName(0), model.getColumnName(1), model.getColumnName(2),
            model.getColumnName(3), model.getColumnName(4) });

    //add rows and cells
    for (int i = 0; i < model.getRowCount(); i++) {
        data.put(Integer.toString(i), new Object[] { getcellvalue(i, 0), getcellvalue(i, 1), getcellvalue(i, 2),
                getcellvalue(i, 3), getcellvalue(i, 4) });

    }/*from   w  ww.j  a  v  a  2  s  .  c o  m*/

    //write to excel
    Set<String> ids = data.keySet();
    XSSFRow row;
    int rowID = 0;
    for (String key : ids) {
        row = ws.createRow(rowID++);

        //get data as per key

        Object[] values = data.get(key);
        int cellID = 0;
        for (Object O : values) {
            XSSFCell cell = row.createCell(cellID++);
            cell.setCellValue(O.toString());
        }
    }

    //write to filesystem
    try

    {
        FileOutputStream fos = new FileOutputStream(new File("E:/excel/daybook.xlsx"));
        wb.write(fos);
        fos.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ex);
    }

}

From source file:minor.UpdateMenu.java

private void writetoexcel() {
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet ws = wb.createSheet();

    //load data to treemap

    TreeMap<String, Object[]> data = new TreeMap<>();

    //add column headers

    data.put("-1", new Object[] { model.getColumnName(0), model.getColumnName(1), model.getColumnName(2) });

    //add rows and cells
    for (int i = 0; i < model.getRowCount(); i++) {
        data.put(Integer.toString(i),
                new Object[] { getcellvalue(i, 0), getcellvalue(i, 1), getcellvalue(i, 2) });

    }//from  w  w w.  jav a 2  s. co  m

    //write to excel
    Set<String> ids = data.keySet();
    XSSFRow row;
    int rowID = 0;
    for (String key : ids) {
        row = ws.createRow(rowID++);

        //get data as per key

        Object[] values = data.get(key);
        int cellID = 0;
        for (Object O : values) {
            XSSFCell cell = row.createCell(cellID++);
            cell.setCellValue(O.toString());
        }
    }

    //write to filesystem
    try

    {
        FileOutputStream fos = new FileOutputStream(new File("E:/excel/menurecords.xlsx"));
        wb.write(fos);
        fos.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ex);
    }

}

From source file:minor.UpdateRecords.java

private void writetoexcel() {
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet ws = wb.createSheet();

    //load data to treemap

    TreeMap<String, Object[]> data = new TreeMap<>();

    //add column headers

    data.put("-1", new Object[] { model.getColumnName(0), model.getColumnName(1), model.getColumnName(2),
            model.getColumnName(3), model.getColumnName(4), model.getColumnName(5), model.getColumnName(6),
            model.getColumnName(7), model.getColumnName(8), model.getColumnName(9) });

    //add rows and cells
    for (int i = 0; i < model.getRowCount(); i++) {
        data.put(Integer.toString(i),
                new Object[] { getcellvalue(i, 0), getcellvalue(i, 1), getcellvalue(i, 2), getcellvalue(i, 3),
                        getcellvalue(i, 4), getcellvalue(i, 5), getcellvalue(i, 6), getcellvalue(i, 7),
                        getcellvalue(i, 8), getcellvalue(i, 9) });

    }//from ww  w  .  j  a v  a  2 s  . c  om

    //write to excel
    Set<String> ids = data.keySet();
    XSSFRow row;
    int rowID = 0;
    for (String key : ids) {
        row = ws.createRow(rowID++);

        //get data as per key

        Object[] values = data.get(key);
        int cellID = 0;
        for (Object O : values) {
            XSSFCell cell = row.createCell(cellID++);
            cell.setCellValue(O.toString());
        }
    }

    //write to filesystem
    try

    {
        FileOutputStream fos = new FileOutputStream(new File("E:/excel/employeerecords.xlsx"));
        wb.write(fos);
        fos.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ex);
    }

}

From source file:mpqq.MPQQ.java

/**
 * This method will check if the index for the row
 * and column are valid and return the cell, if not
 * it will create row and cell based on index.
 *///from   www  .  j  a  v  a 2 s  .  c o  m
private static Cell checkRowCellExists(XSSFSheet currentSheet, int rowIndex, int colIndex) {
    Row currentRow = currentSheet.getRow(rowIndex);
    if (currentRow == null) {
        currentRow = currentSheet.createRow(rowIndex);
    }
    //Check if cell exists
    Cell currentCell = currentRow.getCell(colIndex);
    if (currentCell == null) {
        currentCell = currentRow.createCell(colIndex);
    }
    return currentCell;
}

From source file:mvjce.Excel_operations.java

public static void fill_exceldata(XSSFWorkbook workbook, XSSFSheet spreadsheet) {
    try {//from  www. j  a v  a 2s  . c o m
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Sample_data", "root", "root");
        Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet detail = st.executeQuery(
                "select attendance.USN,Student_info.Name,attendance.sub1_class,attendance.sub2_class,"
                        + " attendance.sub3_class,attendance.sub4_class,attendance.sub5_class,attendance.sub6_class,attendance.sub7_class,attendance.sub8_class from attendance inner join "
                        + " Student_info on attendance.USN = Student_info.USN where class='" + Writesheet.sec
                        + "' and semester=" + Writesheet.sem_string + " ;");
        int i = 1, j = 8;

        XSSFFont font = workbook.createFont();
        font.setFontName("Arial");
        font.setBold(true);
        XSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(XSSFCellStyle.ALIGN_LEFT);
        style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        style.setWrapText(true);
        style.setFont(font);
        XSSFCell cell;
        while (detail.next()) {
            XSSFRow row = spreadsheet.createRow((short) j);
            row.setHeight((short) 900);
            cell = (XSSFCell) row.createCell((short) 0);
            cell.setCellValue(i);
            i++;
            cell.setCellStyle(style);
            cell = (XSSFCell) row.createCell((short) 1);
            cell.setCellValue(detail.getString(1));
            cell.setCellStyle(style);
            cell = (XSSFCell) row.createCell((short) 2);
            cell.setCellValue(detail.getString(2));
            cell.setCellStyle(style);
            cell = (XSSFCell) row.createCell((short) 3);
            cell.setCellValue(detail.getString(3));
            cell.setCellStyle(style);
            cell = (XSSFCell) row.createCell((short) 5);
            cell.setCellValue(detail.getString(4));
            cell.setCellStyle(style);
            cell = (XSSFCell) row.createCell((short) 7);
            cell.setCellValue(detail.getString(5));
            cell.setCellStyle(style);
            cell = (XSSFCell) row.createCell((short) 9);
            cell.setCellValue(detail.getString(6));
            cell.setCellStyle(style);
            cell = (XSSFCell) row.createCell((short) 11);
            cell.setCellValue(detail.getString(7));
            cell.setCellStyle(style);
            cell = (XSSFCell) row.createCell((short) 13);
            cell.setCellValue(detail.getString(8));
            cell.setCellStyle(style);
            cell = (XSSFCell) row.createCell((short) 15);
            cell.setCellValue(detail.getString(9));
            cell.setCellStyle(style);
            cell = (XSSFCell) row.createCell((short) 17);
            cell.setCellValue(detail.getString(10));
            cell.setCellStyle(style);
            j++;
        }

    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:mvjce.Excel_operations.java

public static void insert_internals(XSSFWorkbook workbook, XSSFSheet spreadsheet) {
    try {/*www  .j  a  v a  2s  .co m*/
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Sample_data", "root", "root");
        Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet detail = st.executeQuery(
                "select s.USN,s.Name,i.sub1_int1,i.sub1_int2,i.sub1_int3,i.sub2_int1,i.sub2_int2,i.sub2_int3,i.sub3_int1,i.sub3_int2,i.sub3_int3,i.sub4_int1,i.sub4_int2,i.sub4_int3,\n"
                        + "i2.sub5_int1,i2.sub5_int2,i2.sub5_int3,i2.sub6_int1,i2.sub6_int2,i2.sub6_int3,i2.sub7_int1,i2.sub7_int2,i2.sub7_int3,i2.sub8_int1,i2.sub8_int2,i2.sub8_int3\n"
                        + "from internals as i\n" + "join Student_info as s\n" + "on i.USN=s.USN\n"
                        + "join internals2 as i2\n" + "on i2.USN=s.USN\n" + "where s.Class='" + Writesheet.sec
                        + "' and s.semester=" + Writesheet.sem_string + ";");
        int i = 1, j = 6;
        XSSFFont font = workbook.createFont();
        font.setFontName("Arial");
        font.setBold(true);
        XSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(XSSFCellStyle.ALIGN_LEFT);
        style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        style.setWrapText(true);
        style.setFont(font);
        XSSFCell cell;
        while (detail.next()) {
            XSSFRow row = spreadsheet.createRow((short) j);
            cell = (XSSFCell) row.createCell((short) 0);
            cell.setCellValue(i);
            cell.setCellStyle(style);
            for (int k = 1; k <= 26; k++) {
                cell = (XSSFCell) row.createCell((short) k);
                cell.setCellValue(detail.getString(k));
                cell.setCellStyle(style);
            }
            i++;
            j++;
        }
        spreadsheet.autoSizeColumn(2);
        spreadsheet.autoSizeColumn(1);
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:mvjce.internal_sheet.java

public static void internal_details(XSSFWorkbook workbook) {
    XSSFSheet spreadsheet = workbook.createSheet("test_excel_internal");
    XSSFRow row = spreadsheet.createRow((short) 0);
    XSSFCell cell = (XSSFCell) row.createCell((short) 0);
    cell.setCellValue("MVJ College of Bangalore- 560067");
    //MEARGING CELLS 
    spreadsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 19));
    XSSFFont font = workbook.createFont();
    font.setFontName("Arial");
    font.setBold(true);//  w ww .  j av a2 s .c o  m
    XSSFCellStyle style = workbook.createCellStyle();
    style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
    style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
    style.setWrapText(true);
    style.setFont(font);
    cell.setCellStyle(style);
    Excel_operations.set_subcode();
    row = spreadsheet.createRow((short) 1);
    cell = (XSSFCell) row.createCell((short) 0);
    cell.setCellValue("Department of " + dept_name);
    spreadsheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 19));
    cell.setCellStyle(style);
    row = spreadsheet.createRow(3);
    row.setHeight((short) 600);
    cell = (XSSFCell) row.createCell((short) 1);
    cell.setCellValue("Semester: \n" + sem_string + sec);
    cell.setCellStyle(style);
    row = spreadsheet.createRow(4);
    String[] text = new String[3];
    text[0] = "SI.No";
    text[1] = "USN";
    text[2] = "STUDENT NAME";
    for (int i = 0; i < 3; i++) {
        cell = (XSSFCell) row.createCell((short) i);
        cell.setCellValue(text[i]);
        cell.setCellStyle(style);
        spreadsheet.addMergedRegion(new CellRangeAddress(4, 5, i, i));
    }
    XSSFRow row2 = spreadsheet.createRow((short) 5);
    for (int i = 0, j = 3; j <= 23; j += 4) {
        cell = row.createCell((short) j);
        cell.setCellValue(sub[i]);
        i++;
        cell.setCellStyle(style);
        cell = row2.createCell(j);
        cell.setCellValue("T1");
        cell.setCellStyle(style);
        cell = row2.createCell(j + 1);
        cell.setCellValue("T2");
        cell.setCellStyle(style);
        cell = row2.createCell(j + 2);
        cell.setCellValue("T3");
        cell.setCellStyle(style);
        cell = row2.createCell(j + 3);
        cell.setCellValue("Avg");
        cell.setCellStyle(style);
        spreadsheet.addMergedRegion(new CellRangeAddress(4, 4, j, j + 3));
        Excel_operations.insert_internals(workbook, spreadsheet);
    }
}

From source file:mvjce.Writesheet.java

public static void writesheet() {

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet spreadsheet = workbook.createSheet(sem_string + sec);
    XSSFRow row = spreadsheet.createRow((short) 0);
    XSSFCell cell = (XSSFCell) row.createCell((short) 0);
    cell.setCellValue("MVJ College of Bangalore- 560067");
    //MEARGING CELLS 
    spreadsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 19));
    XSSFFont font = workbook.createFont();
    font.setFontName("Arial");
    font.setBold(true);/*from  w w w.  j  a  v  a  2  s . c o m*/
    XSSFCellStyle style = workbook.createCellStyle();
    style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
    style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
    style.setWrapText(true);
    style.setFont(font);
    cell.setCellStyle(style);
    Excel_operations.set_subcode();
    for (int i = 0; i < 8; i++) {
        internal_sheet.sub[i] = sub[i];
    }
    internal_sheet.dept_name = dept_name;
    internal_sheet.sec = sec;
    internal_sheet.sem_string = sem_string;
    internal_sheet.internal_details(workbook);
    row = spreadsheet.createRow((short) 1);
    cell = (XSSFCell) row.createCell((short) 0);
    cell.setCellValue("Department of " + dept_name);
    spreadsheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 19));
    cell.setCellStyle(style);
    row = spreadsheet.createRow(4);
    row.setHeight((short) 600);
    cell = (XSSFCell) row.createCell((short) 1);
    cell.setCellValue("Semester: \n" + sem_string + sec);
    cell.setCellStyle(style);
    row = spreadsheet.createRow(5);
    String[] text = new String[3];
    text[0] = "SI.No";
    text[1] = "USN";
    text[2] = "STUDENT\nNAME";
    for (int i = 0; i < 3; i++) {
        cell = (XSSFCell) row.createCell((short) i);
        cell.setCellValue(text[i]);
        cell.setCellStyle(style);
        spreadsheet.addMergedRegion(new CellRangeAddress(5, 7, i, i));
    }
    int j = 0;
    XSSFRow row1 = spreadsheet.createRow((short) 6);
    row1.setHeight((short) 1000);
    XSSFRow row2 = spreadsheet.createRow((short) 7);
    row2.setHeight((short) 1000);
    for (int i = 3; i < 18; i++) {
        cell = row1.createCell((short) i);
        cell.setCellValue("Total no. of classes");
        cell.setCellStyle(style);
        cell = row2.createCell((short) i);
        cell.setCellValue("No.of Classes attended");
        cell.setCellStyle(style);
        cell = row2.createCell((short) i + 1);
        cell.setCellValue("%");
        cell.setCellStyle(style);
        cell = row.createCell((short) i);
        cell.setCellValue(sub[j]);
        j++;
        cell.setCellStyle(style);
        spreadsheet.addMergedRegion(new CellRangeAddress(5, 5, i, i + 1));
        i++;
    }
    cell = row1.createCell((short) 19);
    cell.setCellValue("%");
    cell.setCellStyle(style);
    cell = row.createCell((short) 19);
    cell.setCellValue("AVG");
    cell.setCellStyle(style);
    spreadsheet.addMergedRegion(new CellRangeAddress(5, 5, 19, 19));
    Excel_operations.fill_exceldata(workbook, spreadsheet);
    try {
        FileOutputStream out = new FileOutputStream(new File("test_excel.xlsx"));
        workbook.write(out);
        out.close();
    } catch (Exception e) {
        Database.print_error("Excel_output_stream");
    }
    System.out.println("typesofcells.xlsx written successfully");

}

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*  w w  w. j  av a2s . c  o m*/
public void arreglaFechas(OutputStream out) {
    log.debug("Arreglando fechas");
    Date inicio = new Date();
    XSSFWorkbook wb = new XSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    CellStyle cellStyle = wb.createCellStyle();
    cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
    XSSFSheet fechas = wb.createSheet("FECHAS-ANTERIORES");
    int fechasRow = 0;
    XSSFSheet fechas2 = wb.createSheet("FECHAS-POSTERIORES");
    int fechas2Row = 0;
    Transaction tx = null;
    try {
        tx = currentSession().beginTransaction();
        Query update = currentSession()
                .createQuery("update Activo set fechaCompra = :fechaCompra where id = :id");
        Query query = currentSession().createQuery(
                "select new Activo(a.id, a.descripcion, a.fechaCompra, a.tipoActivo.cuenta.id.idCtaMayor, a.centroCosto.id.idCosto, a.codigo) from Activo a where a.fechaCompra < :fechaCompra order by a.tipoActivo.cuenta.id.idCtaMayor, a.centroCosto.id.idCosto, a.codigo");
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        query.setDate("fechaCompra", sdf.parse("01/01/1970"));
        List<Activo> activos = query.list();
        int cont = 0;
        for (Activo activo : activos) {
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(activo.getFechaCompra());
            if (cal1.get(Calendar.YEAR) < 10) {
                log.debug("Pasando al ao 2000 {} - {}", activo.getDescripcion(), activo.getFechaCompra());
                cal1.add(Calendar.YEAR, 2000);
                update.setDate("fechaCompra", cal1.getTime());
                update.setLong("id", activo.getId());
                update.executeUpdate();
                XSSFRow renglon = fechas.createRow(fechasRow++);
                renglon.createCell(0).setCellValue(activo.getTipoActivoCuenta());
                renglon.createCell(1).setCellValue(activo.getCentroCostoCuenta());
                renglon.createCell(2).setCellValue(activo.getCodigo());
                renglon.createCell(3).setCellValue(activo.getDescripcion());
                renglon.createCell(4).setCellValue(sdf.format(activo.getFechaCompra()));
                Cell cell = renglon.createCell(5);
                cell.setCellValue(cal1.getTime());
                cell.setCellStyle(cellStyle);
            } else if (cal1.get(Calendar.YEAR) < 100) {
                log.debug("Pasando al ao 1900 {} - {}", activo.getDescripcion(), activo.getFechaCompra());
                cal1.add(Calendar.YEAR, 1900);
                update.setDate("fechaCompra", cal1.getTime());
                update.setLong("id", activo.getId());
                update.executeUpdate();
                XSSFRow renglon = fechas.createRow(fechasRow++);
                renglon.createCell(0).setCellValue(activo.getTipoActivoCuenta());
                renglon.createCell(1).setCellValue(activo.getCentroCostoCuenta());
                renglon.createCell(2).setCellValue(activo.getCodigo());
                renglon.createCell(3).setCellValue(activo.getDescripcion());
                renglon.createCell(4).setCellValue(sdf.format(activo.getFechaCompra()));
                Cell cell = renglon.createCell(5);
                cell.setCellValue(cal1.getTime());
                cell.setCellStyle(cellStyle);
            } else if (cal1.get(Calendar.YEAR) >= 1900 && cal1.get(Calendar.YEAR) <= 1912) {
                log.debug("Pasando al ao 2000 {} - {}", activo.getDescripcion(), activo.getFechaCompra());
                cal1.add(Calendar.YEAR, 100);
                update.setDate("fechaCompra", cal1.getTime());
                update.setLong("id", activo.getId());
                update.executeUpdate();
                XSSFRow renglon = fechas.createRow(fechasRow++);
                renglon.createCell(0).setCellValue(activo.getTipoActivoCuenta());
                renglon.createCell(1).setCellValue(activo.getCentroCostoCuenta());
                renglon.createCell(2).setCellValue(activo.getCodigo());
                renglon.createCell(3).setCellValue(activo.getDescripcion());
                renglon.createCell(4).setCellValue(sdf.format(activo.getFechaCompra()));
                Cell cell = renglon.createCell(5);
                cell.setCellValue(cal1.getTime());
                cell.setCellStyle(cellStyle);
            }
            cont++;
        }
        currentSession().flush();

        query = currentSession().createQuery(
                "select new Activo(a.id, a.descripcion, a.fechaCompra, a.tipoActivo.cuenta.id.idCtaMayor, a.centroCosto.id.idCosto, a.codigo) from Activo a where a.fechaCompra > :fechaCompra order by a.tipoActivo.cuenta.id.idCtaMayor, a.centroCosto.id.idCosto, a.codigo");
        query.setDate("fechaCompra", new Date());
        activos = query.list();
        for (Activo activo : activos) {
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(activo.getFechaCompra());
            if (cal1.get(Calendar.YEAR) < 2020) {
                log.debug("Quitandole 10 anios {} - {}", activo.getDescripcion(), activo.getFechaCompra());
                cal1.add(Calendar.YEAR, -10);
                update.setDate("fechaCompra", cal1.getTime());
                update.setLong("id", activo.getId());
                update.executeUpdate();
                XSSFRow renglon = fechas2.createRow(fechas2Row++);
                renglon.createCell(0).setCellValue(activo.getTipoActivoCuenta());
                renglon.createCell(1).setCellValue(activo.getCentroCostoCuenta());
                renglon.createCell(2).setCellValue(activo.getCodigo());
                renglon.createCell(3).setCellValue(activo.getDescripcion());
                renglon.createCell(4).setCellValue(sdf.format(activo.getFechaCompra()));
                Cell cell = renglon.createCell(5);
                cell.setCellValue(cal1.getTime());
                cell.setCellStyle(cellStyle);
            } else if (cal1.get(Calendar.YEAR) >= 2020) {
                log.debug("Pasando al ao 1900 {} - {}", activo.getDescripcion(), activo.getFechaCompra());
                cal1.add(Calendar.YEAR, -100);
                update.setDate("fechaCompra", cal1.getTime());
                update.setLong("id", activo.getId());
                update.executeUpdate();
                XSSFRow renglon = fechas2.createRow(fechas2Row++);
                renglon.createCell(0).setCellValue(activo.getTipoActivoCuenta());
                renglon.createCell(1).setCellValue(activo.getCentroCostoCuenta());
                renglon.createCell(2).setCellValue(activo.getCodigo());
                renglon.createCell(3).setCellValue(activo.getDescripcion());
                renglon.createCell(4).setCellValue(sdf.format(activo.getFechaCompra()));
                Cell cell = renglon.createCell(5);
                cell.setCellValue(cal1.getTime());
                cell.setCellStyle(cellStyle);
            }
            cont++;
        }
        currentSession().flush();

        tx.commit();
        log.debug("Termino actualizando {} de {} en {}",
                new Object[] { cont, activos.size(), ((new Date().getTime() - inicio.getTime()) / 1000) });
        wb.write(out);
    } catch (ParseException | HibernateException | IOException e) {
        log.error("No se pudieron arreglar las fechas de los activos", e);
        tx.rollback();
        throw new RuntimeException("No se pudieron arreglar las fechas de los actios", e);
    }
}

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void sube(byte[] datos, Usuario usuario, OutputStream out, Integer codigoInicial) {
    Date inicio = new Date();
    int idx = 5;//from   w ww  .  j  a  v a 2  s . c o m
    int i = 0;
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yy");
    SimpleDateFormat sdf3 = new SimpleDateFormat("dd-MM-yy");

    MathContext mc = new MathContext(16, RoundingMode.HALF_UP);
    NumberFormat nf = NumberFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMaximumFractionDigits(0);
    nf.setMinimumIntegerDigits(5);

    Transaction tx = null;
    try {
        String ejercicioId = "001-2013";
        Map<String, CentroCosto> centrosDeCosto = new HashMap<>();
        Map<String, TipoActivo> tipos = new HashMap<>();
        Query tipoActivoQuery = currentSession()
                .createQuery("select ta from TipoActivo ta " + "where ta.empresa.id = :empresaId "
                        + "and ta.cuenta.id.ejercicio.id.idEjercicio = :ejercicioId "
                        + "and ta.cuenta.id.ejercicio.id.organizacion.id = :organizacionId");
        log.debug("empresaId: {}", usuario.getEmpresa().getId());
        log.debug("ejercicioId: {}", ejercicioId);
        log.debug("organizacionId: {}", usuario.getEmpresa().getOrganizacion().getId());
        tipoActivoQuery.setLong("empresaId", usuario.getEmpresa().getId());
        tipoActivoQuery.setString("ejercicioId", ejercicioId);
        tipoActivoQuery.setLong("organizacionId", usuario.getEmpresa().getOrganizacion().getId());
        List<TipoActivo> listaTipos = tipoActivoQuery.list();
        for (TipoActivo tipoActivo : listaTipos) {
            tipos.put(tipoActivo.getCuenta().getId().getIdCtaMayor(), tipoActivo);
        }
        log.debug("TIPOS: {}", tipos);

        Query proveedorQuery = currentSession().createQuery(
                "select p from Proveedor p where p.empresa.id = :empresaId and p.nombre = :nombreEmpresa");
        proveedorQuery.setLong("empresaId", usuario.getEmpresa().getId());
        proveedorQuery.setString("nombreEmpresa", usuario.getEmpresa().getNombre());
        Proveedor proveedor = (Proveedor) proveedorQuery.uniqueResult();

        Query codigoDuplicadoQuery = currentSession()
                .createQuery("select a from Activo a where a.empresa.id = :empresaId and a.codigo = :codigo");

        XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(datos));
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet ccostoFantasma = wb.createSheet("CCOSTO-FANTASMAS");
        int ccostoFantasmaRow = 0;
        XSSFSheet sinCCosto = wb.createSheet("SIN-CCOSTO");
        int sinCCostoRow = 0;
        XSSFSheet codigoAsignado = wb.createSheet("CODIGO-ASIGNADO");
        int codigoAsignadoRow = 0;
        XSSFSheet fechaInvalida = wb.createSheet("FECHA-INVALIDA");
        int fechaInvalidaRow = 0;
        XSSFSheet sinCosto = wb.createSheet("SIN-COSTO");
        int sinCostoRow = 0;

        //tx = currentSession().beginTransaction();
        for (idx = 5; idx <= 5; idx++) {
            XSSFSheet sheet = workbook.getSheetAt(idx);

            int rows = sheet.getPhysicalNumberOfRows();
            for (i = 2; i < rows; i++) {
                log.debug("Leyendo pagina {} renglon {}", idx, i);
                XSSFRow row = sheet.getRow(i);
                if (row.getCell(0) == null) {
                    break;
                }
                String nombreGrupo = row.getCell(0).getStringCellValue().trim();

                switch (row.getCell(0).getCellType()) {
                case XSSFCell.CELL_TYPE_NUMERIC:
                    nombreGrupo = row.getCell(0).toString().trim();
                    break;
                case XSSFCell.CELL_TYPE_STRING:
                    nombreGrupo = row.getCell(0).getStringCellValue().trim();
                    break;
                }

                TipoActivo tipoActivo = tipos.get(nombreGrupo);
                if (tipoActivo != null) {
                    String cuentaCCosto = row.getCell(2).toString().trim();
                    if (StringUtils.isNotBlank(cuentaCCosto)) {
                        CentroCosto centroCosto = centrosDeCosto.get(cuentaCCosto);
                        if (centroCosto == null) {
                            Query ccostoQuery = currentSession().createQuery("select cc from CentroCosto cc "
                                    + "where cc.id.ejercicio.id.idEjercicio = :ejercicioId "
                                    + "and cc.id.ejercicio.id.organizacion.id = :organizacionId "
                                    + "and cc.id.idCosto like :idCosto");
                            ccostoQuery.setString("ejercicioId", ejercicioId);
                            ccostoQuery.setLong("organizacionId",
                                    usuario.getEmpresa().getOrganizacion().getId());
                            ccostoQuery.setString("idCosto", "1.01." + cuentaCCosto);
                            ccostoQuery.setMaxResults(1);
                            List<CentroCosto> listaCCosto = ccostoQuery.list();
                            if (listaCCosto != null && listaCCosto.size() > 0) {
                                centroCosto = listaCCosto.get(0);
                            }
                            if (centroCosto == null) {
                                XSSFRow renglon = ccostoFantasma.createRow(ccostoFantasmaRow++);
                                renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                                renglon.createCell(1).setCellValue(row.getCell(0).toString());
                                renglon.createCell(2).setCellValue(row.getCell(1).toString());
                                renglon.createCell(3).setCellValue(row.getCell(2).toString());
                                renglon.createCell(4).setCellValue(row.getCell(3).toString());
                                renglon.createCell(5).setCellValue(row.getCell(4).toString());
                                renglon.createCell(6).setCellValue(row.getCell(5).toString());
                                renglon.createCell(7).setCellValue(row.getCell(6).toString());
                                renglon.createCell(8).setCellValue(row.getCell(7).toString());
                                renglon.createCell(9).setCellValue(row.getCell(8).toString());
                                renglon.createCell(10).setCellValue(row.getCell(9).toString());
                                renglon.createCell(11).setCellValue(row.getCell(10).toString());
                                renglon.createCell(12).setCellValue(row.getCell(11).toString());
                                renglon.createCell(13).setCellValue(row.getCell(12).toString());
                                renglon.createCell(14).setCellValue(row.getCell(13).toString());
                                renglon.createCell(15).setCellValue(row.getCell(14).toString());
                                renglon.createCell(16).setCellValue(row.getCell(15).toString());
                                continue;
                            }
                            centrosDeCosto.put(cuentaCCosto, centroCosto);
                        }
                        String poliza = null;
                        switch (row.getCell(4).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            poliza = row.getCell(4).toString();
                            poliza = StringUtils.removeEnd(poliza, ".0");
                            log.debug("POLIZA-N: {}", poliza);
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            poliza = row.getCell(4).getStringCellValue().trim();
                            log.debug("POLIZA-S: {}", poliza);
                            break;
                        }
                        Boolean seguro = false;
                        if (row.getCell(5) != null && StringUtils.isNotBlank(row.getCell(5).toString())) {
                            seguro = true;
                        }
                        Boolean garantia = false;
                        if (row.getCell(6) != null && StringUtils.isNotBlank(row.getCell(6).toString())) {
                            garantia = true;
                        }
                        Date fechaCompra = null;
                        if (row.getCell(7) != null) {
                            log.debug("VALIDANDO FECHA");
                            XSSFCell cell = row.getCell(7);
                            switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_NUMERIC:
                                log.debug("ES NUMERIC");
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    log.debug("ES FECHA");
                                    fechaCompra = cell.getDateCellValue();
                                } else if (DateUtil.isCellInternalDateFormatted(cell)) {
                                    log.debug("ES FECHA INTERNAL");
                                    fechaCompra = cell.getDateCellValue();
                                } else {
                                    BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
                                    bd = stripTrailingZeros(bd);

                                    log.debug("CONVIRTIENDO DOUBLE {} - {}",
                                            DateUtil.isValidExcelDate(bd.doubleValue()), bd);
                                    fechaCompra = HSSFDateUtil.getJavaDate(bd.longValue(), true);
                                    log.debug("Cal: {}", fechaCompra);
                                }
                                break;
                            case Cell.CELL_TYPE_FORMULA:
                                log.debug("ES FORMULA");
                                CellValue cellValue = evaluator.evaluate(cell);
                                switch (cellValue.getCellType()) {
                                case Cell.CELL_TYPE_NUMERIC:
                                    if (DateUtil.isCellDateFormatted(cell)) {
                                        fechaCompra = DateUtil.getJavaDate(cellValue.getNumberValue(), true);
                                    }
                                }
                            }
                        }
                        if (row.getCell(7) != null && fechaCompra == null) {
                            String fechaCompraString;
                            if (row.getCell(7).getCellType() == Cell.CELL_TYPE_STRING) {
                                fechaCompraString = row.getCell(7).getStringCellValue();
                            } else {
                                fechaCompraString = row.getCell(7).toString().trim();
                            }
                            try {
                                fechaCompra = sdf.parse(fechaCompraString);
                            } catch (ParseException e) {
                                try {
                                    fechaCompra = sdf2.parse(fechaCompraString);
                                } catch (ParseException e2) {
                                    try {
                                        fechaCompra = sdf3.parse(fechaCompraString);
                                    } catch (ParseException e3) {
                                        // no se pudo convertir
                                    }
                                }
                            }
                        }

                        if (fechaCompra == null) {
                            XSSFRow renglon = fechaInvalida.createRow(fechaInvalidaRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(row.getCell(8).toString());
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            continue;
                        }

                        String codigo = null;
                        switch (row.getCell(8).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            codigo = row.getCell(8).toString();
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            codigo = row.getCell(8).getStringCellValue().trim();
                            break;
                        }
                        if (StringUtils.isBlank(codigo)) {
                            codigo = "SIN CODIGO" + nf.format(codigoInicial);

                            XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++);

                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue("SIN CODIGO" + codigoInicial);
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            codigoInicial++;
                        } else {
                            // busca codigo duplicado
                            if (codigo.contains(".")) {
                                codigo = codigo.substring(0, codigo.lastIndexOf("."));
                                log.debug("CODIGO: {}", codigo);
                            }

                            codigoDuplicadoQuery.setLong("empresaId", usuario.getEmpresa().getId());
                            codigoDuplicadoQuery.setString("codigo", codigo);
                            Activo activo = (Activo) codigoDuplicadoQuery.uniqueResult();
                            if (activo != null) {
                                XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++);
                                renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                                renglon.createCell(1).setCellValue(row.getCell(0).toString());
                                renglon.createCell(2).setCellValue(row.getCell(1).toString());
                                renglon.createCell(3).setCellValue(row.getCell(2).toString());
                                renglon.createCell(4).setCellValue(row.getCell(3).toString());
                                renglon.createCell(5).setCellValue(row.getCell(4).toString());
                                renglon.createCell(6).setCellValue(row.getCell(5).toString());
                                renglon.createCell(7).setCellValue(row.getCell(6).toString());
                                renglon.createCell(8).setCellValue(row.getCell(7).toString());
                                renglon.createCell(9)
                                        .setCellValue(codigo + "-" + "SIN CODIGO" + nf.format(codigoInicial));
                                renglon.createCell(10).setCellValue(row.getCell(9).toString());
                                renglon.createCell(11).setCellValue(row.getCell(10).toString());
                                renglon.createCell(12).setCellValue(row.getCell(11).toString());
                                renglon.createCell(13).setCellValue(row.getCell(12).toString());
                                renglon.createCell(14).setCellValue(row.getCell(13).toString());
                                renglon.createCell(15).setCellValue(row.getCell(14).toString());
                                renglon.createCell(16).setCellValue(row.getCell(15).toString());
                                codigo = "SIN CODIGO" + nf.format(codigoInicial);
                                codigoInicial++;
                            }
                        }
                        String descripcion = null;
                        if (row.getCell(9) != null) {
                            switch (row.getCell(9).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                descripcion = row.getCell(9).toString();
                                descripcion = StringUtils.removeEnd(descripcion, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                descripcion = row.getCell(9).getStringCellValue().trim();
                                break;
                            default:
                                descripcion = row.getCell(9).toString().trim();
                            }
                        }
                        String marca = null;
                        if (row.getCell(10) != null) {
                            switch (row.getCell(10).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                marca = row.getCell(10).toString();
                                marca = StringUtils.removeEnd(marca, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                marca = row.getCell(10).getStringCellValue().trim();
                                break;
                            default:
                                marca = row.getCell(10).toString().trim();
                            }
                        }
                        String modelo = null;
                        if (row.getCell(11) != null) {
                            switch (row.getCell(11).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                modelo = row.getCell(11).toString();
                                modelo = StringUtils.removeEnd(modelo, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                modelo = row.getCell(11).getStringCellValue().trim();
                                break;
                            default:
                                modelo = row.getCell(11).toString().trim();
                            }
                        }
                        String serie = null;
                        if (row.getCell(12) != null) {
                            switch (row.getCell(12).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                serie = row.getCell(12).toString();
                                serie = StringUtils.removeEnd(serie, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                serie = row.getCell(12).getStringCellValue().trim();
                                break;
                            default:
                                serie = row.getCell(12).toString().trim();
                            }
                        }
                        String responsable = null;
                        if (row.getCell(13) != null) {
                            switch (row.getCell(13).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                responsable = row.getCell(13).toString();
                                responsable = StringUtils.removeEnd(responsable, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                responsable = row.getCell(13).getStringCellValue().trim();
                                break;
                            default:
                                responsable = row.getCell(13).toString().trim();
                            }
                        }

                        String ubicacion = null;
                        if (row.getCell(14) != null) {
                            switch (row.getCell(14).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                ubicacion = row.getCell(14).toString();
                                ubicacion = StringUtils.removeEnd(ubicacion, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                ubicacion = row.getCell(14).getStringCellValue().trim();
                                break;
                            default:
                                ubicacion = row.getCell(14).toString().trim();
                            }
                        }
                        BigDecimal costo = null;
                        switch (row.getCell(15).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            costo = new BigDecimal(row.getCell(15).getNumericCellValue(), mc);
                            log.debug("COSTO-N: {} - {}", costo, row.getCell(15).getNumericCellValue());
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            costo = new BigDecimal(row.getCell(15).toString(), mc);
                            log.debug("COSTO-S: {} - {}", costo, row.getCell(15).toString());
                            break;
                        case XSSFCell.CELL_TYPE_FORMULA:
                            costo = new BigDecimal(
                                    evaluator.evaluateInCell(row.getCell(15)).getNumericCellValue(), mc);
                            log.debug("COSTO-F: {}", costo);
                        }
                        if (costo == null) {
                            XSSFRow renglon = sinCosto.createRow(sinCostoRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(row.getCell(8).toString());
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            continue;
                        }

                        Activo activo = new Activo(fechaCompra, seguro, garantia, poliza, codigo, descripcion,
                                marca, modelo, serie, responsable, ubicacion, costo, tipoActivo, centroCosto,
                                proveedor, usuario.getEmpresa());
                        this.crea(activo, usuario);

                    } else {
                        XSSFRow renglon = sinCCosto.createRow(sinCCostoRow++);
                        renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                        renglon.createCell(1).setCellValue(row.getCell(0).toString());
                        renglon.createCell(2).setCellValue(row.getCell(1).toString());
                        renglon.createCell(3).setCellValue(row.getCell(2).toString());
                        renglon.createCell(4).setCellValue(row.getCell(3).toString());
                        renglon.createCell(5).setCellValue(row.getCell(4).toString());
                        renglon.createCell(6).setCellValue(row.getCell(5).toString());
                        renglon.createCell(7).setCellValue(row.getCell(6).toString());
                        renglon.createCell(8).setCellValue(row.getCell(7).toString());
                        renglon.createCell(9).setCellValue(row.getCell(8).toString());
                        renglon.createCell(10).setCellValue(row.getCell(9).toString());
                        renglon.createCell(11).setCellValue(row.getCell(10).toString());
                        renglon.createCell(12).setCellValue(row.getCell(11).toString());
                        renglon.createCell(13).setCellValue(row.getCell(12).toString());
                        renglon.createCell(14).setCellValue(row.getCell(13).toString());
                        renglon.createCell(15).setCellValue(row.getCell(14).toString());
                        renglon.createCell(16).setCellValue(row.getCell(15).toString());
                        continue;
                    }
                } else {
                    throw new RuntimeException(
                            "(" + idx + ":" + i + ") No se encontro el tipo de activo " + nombreGrupo);
                }
            }
        }
        //tx.commit();
        log.debug("################################################");
        log.debug("################################################");
        log.debug("TERMINO EN {} MINS", (new Date().getTime() - inicio.getTime()) / (1000 * 60));
        log.debug("################################################");
        log.debug("################################################");

        wb.write(out);
    } catch (IOException | RuntimeException e) {
        //if (tx != null && tx.isActive()) {
        //tx.rollback();
        //}
        log.error("Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e);
        throw new RuntimeException(
                "Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e);
    }
}