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:FileHelper.ExcelHelper.java

private void CreateSheetResult(ThreadResult threadR) {
    try {//from w w w .j  av a2  s  . c  om
        File excel = new File("result_threads.xlsx");
        FileInputStream fis = new FileInputStream(excel);
        XSSFWorkbook book = new XSSFWorkbook(fis);
        XSSFSheet sheet = book.createSheet(threadR.getNameSheet());
        // Create Tile Tile
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellValue("Code Result");
        cell = row.createCell(2);
        cell.setCellValue("Response Time (ms)");
        //
        for (int i = 0; i < threadR.getThreads().size(); i++) {
            Row row1 = sheet.createRow(i + 1);
            Cell cell1 = row1.createCell(0);
            cell1.setCellValue(i + 1);

            cell1 = row1.createCell(1);
            cell1.setCellValue(threadR.getThreads().get(i).getCode());

            cell1 = row1.createCell(2);
            cell1.setCellValue(threadR.getThreads().get(i).getTime());
        }
        fis.close();
        FileOutputStream fos = new FileOutputStream(new File("result_threads.xlsx"));
        book.write(fos);
        fos.close();
    } catch (Exception t) {
        System.out.println("Throwable CreateSheetResult " + t.getMessage());
    }
}

From source file:forme.FrmPocetna.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet ws = wb.createSheet();

    TreeMap<String, Object[]> data = new TreeMap<>();
    TblModelPrikazUcinaka dtm = (TblModelPrikazUcinaka) jtblUcinci.getModel();

    Object[] array = new Object[dtm.getColumnCount()];
    for (int i = 0; i < dtm.getColumnCount(); i++) {
        array[i] = dtm.getColumnName(i);
    }/*from ww w  .j a  va 2s. co m*/
    data.put("0", array);

    for (int i = 0; i < dtm.getRowCount(); i++) {
        Object[] niz = new Object[dtm.getColumnCount()];
        for (int j = 0; j < dtm.getColumnCount(); j++) {
            niz[j] = dtm.getValueAt(i, j);
        }
        int rb = i + 1;
        data.put("" + rb, niz);
    }

    Set<String> ids = data.keySet();
    XSSFRow row;
    int rowID = 0;

    for (String key : ids) {
        row = ws.createRow(rowID++);

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

    }

    try {
        FileOutputStream out = new FileOutputStream(new File("../Export/"
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getDomacin().getNaziv()
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getGost().getNaziv()
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getDatumOdigravanja().toString() + ".xlsx"));
        wb.write(out);
        out.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FrmPocetna.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FrmPocetna.class.getName()).log(Level.SEVERE, null, ex);
    }

    JOptionPane.showMessageDialog(this, "Excel fajl uspeno sa?uvan na vaem kompjuteru!",
            "Preuzimanje dovreno", JOptionPane.INFORMATION_MESSAGE);
    try {
        Runtime.getRuntime().exec("cmd.exe /C start ../Export/"
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getDomacin().getNaziv()
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getGost().getNaziv()
                + ((Utakmica) jlistUtakmice.getSelectedValue()).getDatumOdigravanja().toString() + ".xlsx");
        System.out.println("Otvorio");
    } catch (IOException ex) {
        Logger.getLogger(FrmPocetna.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:fr.paris.lutece.plugins.appointment.service.AppointmentUtilities.java

License:Open Source License

/**
 * Build the excel fil of the list of the appointments found in the manage appointment viw by filter
 * /*www.  j  av a2 s  . co  m*/
 * @param strIdForm
 *            the form id
 * @param response
 *            the response
 * @param locale
 *            the local
 * @param listAppointmentsDTO
 *            the list of the appointments to input in the excel file
 * @param stateService
 *            the state service
 */
public static void buildExcelFileWithAppointments(String strIdForm, HttpServletResponse response, Locale locale,
        List<AppointmentDTO> listAppointmentsDTO, StateService stateService) {
    AppointmentFormDTO tmpForm = FormService.buildAppointmentFormLight(Integer.parseInt(strIdForm));
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet(I18nService.getLocalizedString(KEY_RESOURCE_TYPE, locale));
    List<Object[]> tmpObj = new ArrayList<Object[]>();
    EntryFilter entryFilter = new EntryFilter();
    entryFilter.setIdResource(Integer.valueOf(strIdForm));
    List<Entry> listEntry = EntryHome.getEntryList(entryFilter);
    Map<Integer, String> mapDefaultValueGenAttBackOffice = new HashMap<Integer, String>();
    for (Entry e : listEntry) {
        if (e.isOnlyDisplayInBack()) {
            e = EntryHome.findByPrimaryKey(e.getIdEntry());
            if (e.getFields() != null && e.getFields().size() == 1
                    && !StringUtils.isEmpty(e.getFields().get(0).getValue())) {
                mapDefaultValueGenAttBackOffice.put(e.getIdEntry(), e.getFields().get(0).getValue());
            } else if (e.getFields() != null) {
                for (Field field : e.getFields()) {
                    if (field.isDefaultValue()) {
                        mapDefaultValueGenAttBackOffice.put(e.getIdEntry(), field.getValue());
                    }
                }
            }
        }
    }
    int nTaille = 10 + (listEntry.size() + 1);
    if (tmpForm != null) {
        int nIndex = 0;
        Object[] strWriter = new String[1];
        strWriter[0] = tmpForm.getTitle();
        tmpObj.add(strWriter);
        Object[] strInfos = new String[nTaille];
        strInfos[0] = I18nService.getLocalizedString(KEY_COLUMN_LAST_NAME, locale);
        strInfos[1] = I18nService.getLocalizedString(KEY_COLUMN_FISRT_NAME, locale);
        strInfos[2] = I18nService.getLocalizedString(KEY_COLUMN_EMAIL, locale);
        strInfos[3] = I18nService.getLocalizedString(KEY_COLUMN_DATE_APPOINTMENT, locale);
        strInfos[4] = I18nService.getLocalizedString(KEY_TIME_START, locale);
        strInfos[5] = I18nService.getLocalizedString(KEY_TIME_END, locale);
        strInfos[6] = I18nService.getLocalizedString(KEY_COLUMN_ADMIN, locale);
        strInfos[7] = I18nService.getLocalizedString(KEY_COLUMN_STATUS, locale);
        strInfos[8] = I18nService.getLocalizedString(KEY_COLUMN_STATE, locale);
        strInfos[9] = I18nService.getLocalizedString(KEY_COLUMN_NB_BOOKED_SEATS, locale);
        nIndex = 1;
        if (listEntry.size() > 0) {
            for (Entry e : listEntry) {
                strInfos[10 + nIndex] = e.getTitle();
                nIndex++;
            }
        }
        tmpObj.add(strInfos);
    }
    if (listAppointmentsDTO != null) {
        for (AppointmentDTO appointmentDTO : listAppointmentsDTO) {
            int nIndex = 0;
            Object[] strWriter = new String[nTaille];
            strWriter[0] = appointmentDTO.getLastName();
            strWriter[1] = appointmentDTO.getFirstName();
            strWriter[2] = appointmentDTO.getEmail();
            strWriter[3] = appointmentDTO.getDateOfTheAppointment();
            strWriter[4] = appointmentDTO.getStartingTime().toString();
            strWriter[5] = appointmentDTO.getEndingTime().toString();
            strWriter[6] = appointmentDTO.getAdminUser();
            String status = I18nService.getLocalizedString(AppointmentDTO.PROPERTY_APPOINTMENT_STATUS_RESERVED,
                    locale);
            if (appointmentDTO.getIsCancelled()) {
                status = I18nService.getLocalizedString(AppointmentDTO.PROPERTY_APPOINTMENT_STATUS_UNRESERVED,
                        locale);
            }
            strWriter[7] = status;
            State stateAppointment = stateService.findByResource(appointmentDTO.getIdAppointment(),
                    Appointment.APPOINTMENT_RESOURCE_TYPE, tmpForm.getIdWorkflow());
            String strState = StringUtils.EMPTY;
            if (stateAppointment != null) {
                appointmentDTO.setState(stateAppointment);
                strState = stateAppointment.getName();
            }
            strWriter[8] = strState;
            nIndex = 1;
            strWriter[9] = Integer.toString(appointmentDTO.getNbBookedSeats());
            List<Integer> listIdResponse = AppointmentResponseService
                    .findListIdResponse(appointmentDTO.getIdAppointment());
            List<Response> listResponses = new ArrayList<Response>();
            for (int nIdResponse : listIdResponse) {
                Response resp = ResponseHome.findByPrimaryKey(nIdResponse);
                if (resp != null) {
                    listResponses.add(resp);
                }
            }
            for (Entry e : listEntry) {
                Integer key = e.getIdEntry();
                StringBuffer strValue = new StringBuffer(StringUtils.EMPTY);
                String strPrefix = StringUtils.EMPTY;
                for (Response resp : listResponses) {
                    String strRes = StringUtils.EMPTY;
                    if (key.equals(resp.getEntry().getIdEntry())) {
                        Field f = resp.getField();
                        int nfield = 0;
                        if (f != null) {
                            nfield = f.getIdField();
                            Field field = FieldHome.findByPrimaryKey(nfield);
                            if (field != null) {
                                strRes = field.getTitle();
                            }
                        } else {
                            strRes = resp.getResponseValue();
                        }
                    }
                    if ((strRes != null) && !strRes.isEmpty()) {
                        strValue.append(strPrefix + strRes);
                        strPrefix = CONSTANT_COMMA;
                    }
                }
                if (strValue.toString().isEmpty() && mapDefaultValueGenAttBackOffice.containsKey(key)) {
                    strValue.append(mapDefaultValueGenAttBackOffice.get(key));
                }
                if (!strValue.toString().isEmpty()) {
                    strWriter[10 + nIndex] = strValue.toString();
                }
                nIndex++;
            }
            tmpObj.add(strWriter);
        }
    }
    int nRownum = 0;
    for (Object[] myObj : tmpObj) {
        Row row = sheet.createRow(nRownum++);
        int nCellnum = 0;
        for (Object strLine : myObj) {
            Cell cell = row.createCell(nCellnum++);
            if (strLine instanceof String) {
                cell.setCellValue((String) strLine);
            } else if (strLine instanceof Boolean) {
                cell.setCellValue((Boolean) strLine);
            } else if (strLine instanceof Date) {
                cell.setCellValue((Date) strLine);
            } else if (strLine instanceof Double) {
                cell.setCellValue((Double) strLine);
            }
        }
    }
    try {
        String now = new SimpleDateFormat("yyyyMMdd-hhmm")
                .format(GregorianCalendar.getInstance(locale).getTime()) + "_"
                + I18nService.getLocalizedString(KEY_RESOURCE_TYPE, locale) + EXCEL_FILE_EXTENSION;
        response.setContentType(EXCEL_MIME_TYPE);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + now + "\";");
        response.setHeader("Pragma", "public");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate,post-check=0,pre-check=0");
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        os.close();
        workbook.close();
    } catch (IOException e) {
        AppLogService.error(e);
    }
}

From source file:gov.anl.cue.arcane.engine.matrix.MatrixEngine.java

License:Open Source License

/**
 * Creates the row header./*  ww w .j a v a2 s .  c o m*/
 *
 * @param workbook the workbook
 * @param sheet the sheet
 * @param rowIndex the row index
 * @param label1 the label1
 * @param label2 the label2
 */
public void createRowHeader(XSSFWorkbook workbook, XSSFSheet sheet, int rowIndex, String label1,
        String label2) {

    // Create the needed highlight style.
    XSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
    cellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(197, 217, 241)));
    cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
    XSSFFont font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    cellStyle.setFont(font);

    // Create the requested row.
    XSSFRow row = sheet.createRow(0);
    XSSFCell cell = row.createCell(0);
    cell.setCellValue(label1);
    cell.setCellStyle(cellStyle);
    cell = row.createCell(1);
    cell.setCellValue(label2);
    cell.setCellStyle(cellStyle);

}

From source file:gov.anl.cue.arcane.engine.matrix.MatrixEngine.java

License:Open Source License

/**
 * Creates the row int.//from  w  w w  . ja  v  a2 s .  c  om
 *
 * @param sheet the sheet
 * @param rowIndex the row index
 * @param label the label
 * @param value the value
 */
public void createRowInt(XSSFSheet sheet, int rowIndex, String label, int value) {

    // Create the requested row.
    XSSFRow row = sheet.createRow(rowIndex);
    XSSFCell cell = row.createCell(0);
    cell.setCellValue(label);
    cell = row.createCell(1);
    cell.setCellValue(value);

}

From source file:gov.anl.cue.arcane.engine.matrix.MatrixEngine.java

License:Open Source License

/**
 * Creates the row double.//from  www  .java  2  s.  c  o  m
 *
 * @param sheet the sheet
 * @param rowIndex the row index
 * @param label the label
 * @param value the value
 */
public void createRowDouble(XSSFSheet sheet, int rowIndex, String label, double value) {

    // Create the requested row.
    XSSFRow row = sheet.createRow(rowIndex);
    XSSFCell cell = row.createCell(0);
    cell.setCellValue(label);
    cell = row.createCell(1);
    cell.setCellValue(value);

}

From source file:gov.anl.cue.arcane.engine.matrix.MatrixModel.java

License:Open Source License

/**
 * Write scan variables.// w  ww .j  a va2 s.co m
 *
 * @param workbook the workbook
 * @param cellStyle the cell style
 * @throws OutOfRangeException the out of range exception
 */
public void writeScanVariables(XSSFWorkbook workbook, XSSFCellStyle cellStyle) throws OutOfRangeException {

    // Scan the variables.
    for (MatrixVariable matrixVariable : this) {

        // Fill in a header.
        XSSFSheet sheet = workbook
                .createSheet(matrixVariable.name + " (" + matrixVariable.units.getUnit() + ")");
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue("Equation");
        cell.setCellStyle(cellStyle);
        cell = row.createCell(1);
        cell.setCellValue("Node");
        cell.setCellStyle(cellStyle);
        for (int rowIndex = 0; rowIndex < matrixVariable.equations.size(); rowIndex++) {
            cell = row.createCell(rowIndex + 2);
            cell.setCellValue(this.nodeName(rowIndex));
            cell.setCellStyle(cellStyle);
        }

        // Fill in the main rows.
        for (int rowIndex = 0; rowIndex < matrixVariable.equations.size(); rowIndex++) {

            // Create the next row.
            row = sheet.createRow(rowIndex + 1);

            // Create the equation column.
            cell = row.createCell(0);
            cell.setCellValue(matrixVariable.equations.get(rowIndex));

            // Create the node index column.
            cell = row.createCell(1);
            cell.setCellValue(this.nodeName(rowIndex));
            cell.setCellStyle(cellStyle);

            // Fill in the coefficients.
            for (int columnIndex = 0; columnIndex < matrixVariable.equations.size(); columnIndex++) {
                cell = row.createCell(columnIndex + 2);
                double cellValue = matrixVariable.coefficients.getEntry(rowIndex, columnIndex);
                if (!Double.isNaN(cellValue)) {
                    cell.setCellValue(cellValue);
                }
            }

        }

    }

}

From source file:gov.anl.cue.arcane.engine.matrix.MatrixModel.java

License:Open Source License

/**
 * Write fitness function information.//from w  w  w  .ja  va  2  s  . c  o  m
 *
 * @param workbook the workbook
 * @param cellStyle the cell style
 * @return the XSSF sheet
 */
public XSSFSheet writeFitnessFunctionInformation(XSSFWorkbook workbook, XSSFCellStyle cellStyle) {

    // Fill in the fitness header.
    XSSFSheet sheet = workbook.createSheet("Fitness");
    XSSFRow row = sheet.createRow(0);
    XSSFCell cell = row.createCell(0);
    cell.setCellValue("Equation");
    cell.setCellStyle(cellStyle);
    cell = row.createCell(1);
    cell.setCellValue("Node");
    cell.setCellStyle(cellStyle);

    // Fill in the fitness equations.
    for (int rowIndex = 0; rowIndex < fitnessEquations.size(); rowIndex++) {

        // Create the next row.
        row = sheet.createRow(rowIndex + 1);

        // Create the equation column.
        cell = row.createCell(0);
        cell.setCellValue(this.fitnessEquations.get(rowIndex));

        // Create the node index column.
        cell = row.createCell(1);
        cell.setCellValue(this.nodeName(rowIndex));
        cell.setCellStyle(cellStyle);

    }

    // Fill in the fitness value footer.
    row = sheet.createRow(fitnessEquations.size() + 1);
    cell = row.createCell(0);
    if (this.fitnessFunctionType == MatrixModel.FITNESS_FUNCTION_TYPE.SIMPLE_MAXIMUM) {
        cell.setCellValue(MatrixModel.SIMPLE_MAXIMUM_STRING);
    } else if (this.fitnessFunctionType == MatrixModel.FITNESS_FUNCTION_TYPE.USER_EQUATION) {
        cell.setCellValue(MatrixModel.SYSTEM_DYNAMICS_STRING);
    } else {
        cell.setCellValue(MatrixModel.ZERO_FITNESS_STRING);
    }
    cell = row.createCell(1);
    if (!Double.isNaN(this.getFitnessValue())) {
        cell.setCellValue(this.getFitnessValue());
    }

    // Fill in the step count and size.
    if (this.fitnessFunctionType == MatrixModel.FITNESS_FUNCTION_TYPE.USER_EQUATION) {
        row = sheet.createRow(fitnessEquations.size() + 2);
        cell = row.createCell(0);
        cell.setCellValue(MatrixModel.SYSTEM_DYNAMICS_STEP_COUNT_STRING);
        cell = row.createCell(1);
        cell.setCellValue(this.stepCount);
        row = sheet.createRow(fitnessEquations.size() + 3);
        cell = row.createCell(0);
        cell.setCellValue(MatrixModel.SYSTEM_DYNAMICS_STEP_SIZE_STRING);
        cell = row.createCell(1);
        cell.setCellValue(this.stepSize);
        row = sheet.createRow(fitnessEquations.size() + 4);
        cell = row.createCell(0);
        cell.setCellValue(MatrixModel.SYSTEM_DYNAMICS_GROW_STRING);
        cell = row.createCell(1);
        if (this.equationEvolution) {
            cell.setCellValue("Yes");
        } else {
            cell.setCellValue("No");
        }

    }

    // Return the results.
    return sheet;

}

From source file:gov.nih.nci.evs.app.neopl.CSVtoExcel.java

License:Open Source License

public void runXSSF(String inputfile) {
    int size = checkSpecialCharacters(inputfile);

    int n = inputfile.lastIndexOf(".");
    //String outputfile = inputfile.substring(0, n) + ".xlsx";
    String outputfile = getOutputFile(inputfile, ".xlsx");

    try {/*from   w w w  .  j a  va2s . c o m*/
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFCreationHelper helper = null;

        XSSFCellStyle cellStyle = wb.createCellStyle();
        XSSFFont font = wb.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        cellStyle.setFont(font);

        XSSFCellStyle linkCellStyle = wb.createCellStyle();
        XSSFFont linkfont = wb.createFont();

        //XSSFColor color = new XSSFColor(Color.LIGHT_BLUE);
        XSSFColor color = new XSSFColor(Color.BLUE);
        linkfont.setColor(color);

        //linkfont.setColor(XSSFColor.LIGHT_BLUE.index);
        linkCellStyle.setFont(linkfont);
        CSVReader reader = new CSVReader(new FileReader(inputfile));//CSV file
        String[] line;
        int r = 0;
        Cell cell = null;

        XSSFHyperlink url_link = null;
        XSSFSheet sheet = null;

        int page_num = 1;
        Row row = null;
        int lcv = 0;
        int row_count = 0;

        try {

            while ((line = reader.readNext()) != null) {
                if (lcv % PAGE_SIZE == 0) {
                    r = 0;
                    String sheetLabel = SHEET_LABEL;
                    if (size > PAGE_SIZE) {
                        sheetLabel = sheetLabel + " (Page " + page_num + ")";
                    }
                    //System.out.println("Creating " + sheetLabel);
                    sheet = wb.createSheet(sheetLabel);
                    helper = sheet.getWorkbook().getCreationHelper();
                    url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);

                    row = sheet.createRow((short) r);
                    for (int i = 0; i < HEADINGS.length; i++) {
                        String heading = HEADINGS[i];
                        cell = row.createCell(i);
                        cell.setCellValue(heading);
                        cell.setCellStyle(cellStyle);
                    }
                    page_num++;

                } else {
                    String s4 = (String) line[4];
                    s4 = s4.trim();
                    r++;
                    row = sheet.createRow((short) r);
                    row_count++;
                    cell = row.createCell(0);
                    String ncit_code = line[0];
                    cell.setCellValue(ncit_code);
                    if (NCIT_LINK) {
                        url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);
                        url_link.setAddress(getNCItHyperlink(ncit_code));
                        cell.setHyperlink(url_link);
                        cell.setCellStyle(linkCellStyle);
                    }

                    cell = row.createCell(1);
                    String name = line[1];
                    cell.setCellValue(line[1]);

                    cell = row.createCell(2);
                    cell.setCellValue(line[2]);
                    if (NCIM_LINK) {
                        String s2 = line[2];
                        s2 = s2.trim();
                        if (s2.length() > 0) {
                            url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);
                            url_link.setAddress(getNCImHyperlink(s2));
                            cell.setHyperlink(url_link);
                            cell.setCellStyle(linkCellStyle);
                        }
                    }

                    cell = row.createCell(3);
                    String ncim_name = line[3];
                    cell.setCellValue(line[3]);

                    cell = row.createCell(4);
                    cell.setCellValue(line[4]);

                    cell = row.createCell(5);
                    String atom_name = (String) line[5];
                    cell.setCellValue(line[5]);

                    cell = row.createCell(6);
                    cell.setCellValue(line[6]);

                    if (SOURCE_LINK) {
                        if (s4.length() > 0) {
                            String s6 = (String) line[6];
                            if (localNameMap.containsKey(s4)) {
                                url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL);
                                s4 = (String) localNameMap.get(s4);
                                url_link.setAddress(getSourceHyperlink(s4, s6));
                                cell.setHyperlink(url_link);
                                cell.setCellStyle(linkCellStyle);
                            }
                        }
                    }
                    cell = row.createCell(7);
                    cell.setCellValue(line[7]);
                }
                lcv++;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // Write the output to a file
        FileOutputStream fileOut = new FileOutputStream(outputfile);
        wb.write(fileOut);
        fileOut.close();
        System.out.println("Output file " + outputfile + " generated.");
        System.out.println("row_count: " + row_count);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Group1.ReportServlet1.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // create the workbook, its worksheet, and its title row
    List<String[]> apppp = new LinkedList<String[]>();

    try {//from   ww w . j  a v a 2s .  c om
        // read database rowsgetConnection(
        Connection connection = DatabaseConnection.getConnection("toba", "root", "root");
        Statement statement = connection.createStatement();
        String query = "SELECT * FROM user ORDER BY Username";
        ResultSet results = statement.executeQuery(query);

        // create the spreadsheet rows
        int i = 3;
        while (results.next()) {
            String[] appp = new String[9];
            appp[0] = "" + results.getString("Username");
            appp[1] = "" + (results.getString("Firstname"));
            appp[2] = "" + (results.getString("Lastname"));
            appp[3] = "" + (results.getString("Phone"));
            appp[4] = "" + (results.getString("Address"));
            appp[5] = "" + (results.getString("City"));
            appp[6] = "" + (results.getString("State"));
            appp[7] = "" + (results.getString("Zipcode"));
            appp[8] = "" + (results.getString("Email"));
            apppp.add(appp);
        }
        results.close();
        statement.close();
        DatabaseConnection.closeConnection(connection);
    } catch (SQLException e) {
        e.printStackTrace();
        this.log(e.toString());
    }

    String[][] args = new String[apppp.size()][9];

    for (int i = 0; i < apppp.size(); i++) {
        args[i] = apppp.get(i);
    }

    String[] columnNames = new String[] { "User Name", "First Name", " Last Name", "Phone", "ADdress", "City",
            "State", "Zip Code", "Email" };

    XSSFWorkbook workbook = new XSSFWorkbook();

    //Create a blank sheet
    XSSFSheet sheet = workbook.createSheet("Employee Data");

    //This data needs to be written (Object[])
    int rownum = 0;
    Row row;
    Cell cell;
    int j = 0;
    row = sheet.createRow(0);

    for (j = 0; j < columnNames.length; j++) {
        cell = row.createCell(j);
        cell.setCellValue(columnNames[j]);
    }

    for (int i = 0; i < args.length; i++) {
        row = sheet.createRow(i + 1);
        for (j = 0; j < args[0].length; j++) {
            cell = row.createCell(j);
            cell.setCellValue(args[i][j]);
        }
    }
    try {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("content-disposition", "attachment; filename=users.xlsx");
        response.setHeader("cache-control", "no-cache");
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.close();
        //Write the workbook in file system
        /*FileOutputStream out = new FileOutputStream(new File(filename));
        workbook.write(out);
        out.close();
        System.out.println(filename+ " written successfully on disk.");*/
    } catch (Exception e) {
        e.printStackTrace();
    }

    // set the response headers

    // get the output stream and send the workbook to the browser

}