Example usage for org.apache.poi.ss.usermodel Row createCell

List of usage examples for org.apache.poi.ss.usermodel Row createCell

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Row createCell.

Prototype

Cell createCell(int column);

Source Link

Document

Use this to create new cells within the row and return it.

Usage

From source file:com.hp.action.StaffHistoryAction.java

public String exportExcel() {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();

    user = (User) session.getAttribute("USER");

    //Authorize//from w  w  w  .  ja v  a  2s .  c  o m
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    //GET DATA
    listStaffHistory = (List<StaffHistory>) session.getAttribute("listStaffHistory");

    if (listStaffHistory == null)
        return INPUT;

    String fileInput = ServletActionContext.getServletContext().getRealPath("/db_exports/");
    String start = (String) session.getAttribute("startDate");
    String end = (String) session.getAttribute("endDate");

    //
    //Write
    HSSFWorkbook workBook = new HSSFWorkbook();
    HSSFSheet sheet = workBook.createSheet("Chm sc khch hng");
    //sheet.autoSizeColumn(200);
    sheet.setColumnWidth(0, 1000);
    sheet.setDefaultColumnWidth(20);

    //TakeOrder title
    for (int i = 1; i < 2; i++) {
        //
        Row rowstart = sheet.createRow(0);

        //Row Title
        Row row0 = sheet.createRow(i);
        row0.setHeight((short) 500);
        Cell cell0 = row0.createCell(0);

        //Merge for title
        sheet.addMergedRegion(new CellRangeAddress(i, //first row (0-based)
                i, //last row  (0-based)
                0, //first column (0-based)
                5 //last column  (0-based)
        ));
        //CellUtil.setAlignment(cell0, workBook, CellStyle.ALIGN_CENTER);
        CellStyle cellStyle = workBook.createCellStyle();
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);

        //font
        Font headerFont = workBook.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setFontHeight((short) 250);
        cellStyle.setFont(headerFont);

        cell0.setCellStyle(cellStyle);
        cell0.setCellValue("Bo co chm sc khch hng");

        //Row date
        Row row1 = sheet.createRow(i + 1);
        //row1.setHeight((short)500);
        Cell cell1 = row1.createCell(0);

        //Merge for title
        sheet.addMergedRegion(new CellRangeAddress(i + 1, //first row (0-based)
                i + 1, //last row  (0-based)
                0, //first column (0-based)
                5 //last column  (0-based)
        ));
        CellStyle cellAlign = workBook.createCellStyle();
        cellAlign.setAlignment(CellStyle.ALIGN_CENTER);
        cell1.setCellStyle(cellAlign);

        if (start == null)
            start = "";
        if (end == null)
            end = "";
        cell1.setCellValue("T ngy: " + start + " - ?n ngy: " + end);

        //Row Header
        Row row = sheet.createRow(4);
        int cellnum = 0;

        for (Object obj : titleArray()) {
            Cell cell = row.createCell(cellnum++);

            CellStyle style = workBook.createCellStyle();
            style.setFillForegroundColor(HSSFColor.YELLOW.index);
            style.setFillPattern(CellStyle.SOLID_FOREGROUND);

            cell.setCellStyle(style);

            if (obj instanceof Timestamp)
                cell.setCellValue((Timestamp) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Float)
                cell.setCellValue((Float) obj);
        }

    }
    //Write TakeOrder
    for (int i = 0; i < listStaffHistory.size(); i++) {
        Row row = sheet.createRow(i + 5);
        int cellnum = 0;

        //Cell 0 - stt
        Cell cell0 = row.createCell(cellnum++);
        cell0.setCellValue(i + 1);

        //Set content
        for (Object obj : objectArray(listStaffHistory.get(i))) {
            Cell cell = row.createCell(cellnum++);

            if (obj instanceof Timestamp)
                cell.setCellValue((Timestamp) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof Integer)
                cell.setCellValue((Integer) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Float) {

                //                    CellStyle cellStyle = workBook.createCellStyle();
                //                    DataFormat format = workBook.createDataFormat();
                //                    cellStyle.setDataFormat(format.getFormat("#.#"));
                //                    cell.setCellStyle(cellStyle);

                cell.setCellValue((Float) obj);
            } else if (obj instanceof Double)
                cell.setCellValue((Double) obj);
        }

    }

    outputFile = "BaoCaoChamSocKhachHang" + start + " - " + end + ".xls";
    try {
        FileOutputStream output = new FileOutputStream(new File(fileInput + "\\" + outputFile));

        workBook.write(output);
        output.close();
        System.out.println("Excel written successfully..");
        orderFile = new FileInputStream(new File(fileInput + "\\" + outputFile));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return SUCCESS;
}

From source file:com.hp.action.StaffsAction.java

public String exportExcel() {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();

    //Authorize/*from   ww  w .j  a va2 s. c o  m*/
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    //GET DATA
    staffsList = (List<Staff>) session.getAttribute("staffsList");

    if (staffsList == null)
        return INPUT;

    String fileInput = ServletActionContext.getServletContext().getRealPath("/db_exports/");

    //
    //Write
    HSSFWorkbook workBook = new HSSFWorkbook();
    HSSFSheet sheet = workBook.createSheet("Nhn vin");
    //sheet.autoSizeColumn(200);
    sheet.setColumnWidth(0, 1000);
    sheet.setDefaultColumnWidth(20);

    //TakeOrder title
    for (int i = 1; i < 2; i++) {
        //
        Row rowstart = sheet.createRow(0);

        //Row Title
        Row row0 = sheet.createRow(i);
        row0.setHeight((short) 500);
        Cell cell0 = row0.createCell(0);

        //Merge for title
        sheet.addMergedRegion(new CellRangeAddress(i, //first row (0-based)
                i, //last row  (0-based)
                0, //first column (0-based)
                10 //last column  (0-based)
        ));
        //CellUtil.setAlignment(cell0, workBook, CellStyle.ALIGN_CENTER);
        CellStyle cellStyle = workBook.createCellStyle();
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);

        //font
        Font headerFont = workBook.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setFontHeight((short) 250);
        cellStyle.setFont(headerFont);

        cell0.setCellStyle(cellStyle);
        cell0.setCellValue("Danh sch nhn vin");

        //Row date
        Row row1 = sheet.createRow(i + 1);
        //row1.setHeight((short)500);
        Cell cell1 = row1.createCell(0);

        //Merge for title
        sheet.addMergedRegion(new CellRangeAddress(i + 1, //first row (0-based)
                i + 1, //last row  (0-based)
                0, //first column (0-based)
                10 //last column  (0-based)
        ));
        CellStyle cellAlign = workBook.createCellStyle();
        cellAlign.setAlignment(CellStyle.ALIGN_CENTER);
        cell1.setCellStyle(cellAlign);

        cell1.setCellValue("");

        //Row Header
        Row row = sheet.createRow(4);
        int cellnum = 0;

        for (Object obj : titleArray()) {
            Cell cell = row.createCell(cellnum++);

            CellStyle style = workBook.createCellStyle();
            style.setFillForegroundColor(HSSFColor.YELLOW.index);
            style.setFillPattern(CellStyle.SOLID_FOREGROUND);

            cell.setCellStyle(style);

            if (obj instanceof Timestamp)
                cell.setCellValue((Timestamp) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Float)
                cell.setCellValue((Float) obj);
        }

    }
    //Write TakeOrder
    for (int i = 0; i < staffsList.size(); i++) {
        Row row = sheet.createRow(i + 5);
        int cellnum = 0;

        //Cell 0 - stt
        Cell cell0 = row.createCell(cellnum++);
        cell0.setCellValue(i + 1);

        //Set content
        for (Object obj : objectArray(staffsList.get(i))) {
            Cell cell = row.createCell(cellnum++);

            if (obj instanceof Timestamp)
                cell.setCellValue((Timestamp) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof Integer)
                cell.setCellValue((Integer) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Float) {

                //                    CellStyle cellStyle = workBook.createCellStyle();
                //                    DataFormat format = workBook.createDataFormat();
                //                    cellStyle.setDataFormat(format.getFormat("#.#"));
                //                    cell.setCellStyle(cellStyle);

                cell.setCellValue((Float) obj);
            } else if (obj instanceof Double)
                cell.setCellValue((Double) obj);
        }

    }

    outputFile = "DanhSachNhanVien.xls";
    try {
        FileOutputStream output = new FileOutputStream(new File(fileInput + "\\" + outputFile));

        workBook.write(output);
        output.close();
        System.out.println("Excel written successfully..");
        orderFile = new FileInputStream(new File(fileInput + "\\" + outputFile));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return SUCCESS;
}

From source file:com.hp.action.TakeOrderAction.java

public String exportOrders() {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();

    //Authorize/*  ww w .  ja v a 2  s .  c  o m*/
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    staffList = staffDAO.getListUser(null);

    String fileInput = ServletActionContext.getServletContext().getRealPath("/database/");
    System.out.println("Result: " + staff + " from date: " + fromDate + " , to date: " + toDate);

    takeOrdersList = takeOrderDAO.getTakeOrdersList(staff, fromDate, toDate);
    if (takeOrdersList.isEmpty())
        return INPUT;

    Map<String, List<TakeOrderDetail>> data = new HashMap<String, List<TakeOrderDetail>>();

    for (int i = 0; i < takeOrdersList.size(); i++) {
        data.put(i + "", takeOrderDetailDAO.getDetailTakeOrdersList(takeOrdersList.get(i).getId()));

    }

    int line = 0;
    Set<String> keyset = data.keySet();

    for (String key : keyset) {
        line += data.get(key).size();
    }

    line += keyset.size();

    //Write
    HSSFWorkbook workBook = new HSSFWorkbook();
    HSSFSheet sheet = workBook.createSheet("Order");

    //TakeOrder title
    for (int i = 0; i < 1; i++) {
        Row row = sheet.createRow(i);
        int cellnum = 0;

        for (Object obj : takeOrdersList.get(i).toTitleArray()) {
            Cell cell = row.createCell(cellnum++);

            if (obj instanceof Timestamp)
                cell.setCellValue((Timestamp) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Float)
                cell.setCellValue((Float) obj);
        }
    }
    //Write TakeOrder
    for (int i = 0; i < takeOrdersList.size(); i++) {
        Row row = sheet.createRow(i + 1);
        int cellnum = 0;

        for (Object obj : takeOrdersList.get(i).toArray()) {
            Cell cell = row.createCell(cellnum++);

            if (obj instanceof Timestamp)
                cell.setCellValue((Timestamp) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Float)
                cell.setCellValue((Float) obj);
        }
    }

    //Write TakeOrderDetail title
    for (String key : keyset) {
        for (int i = 0; i < 1; i++) {
            Row row = sheet.createRow(i + takeOrdersList.size() + 3);
            int cellnum = 0;
            for (Object obj : data.get(key).get(i).toTitleArray()) {
                Cell cell = row.createCell(cellnum++);

                if (obj instanceof Timestamp)
                    cell.setCellValue((Timestamp) obj);
                else if (obj instanceof Boolean)
                    cell.setCellValue((Boolean) obj);
                else if (obj instanceof String)
                    cell.setCellValue((String) obj);
                else if (obj instanceof Float)
                    cell.setCellValue((Float) obj);
                else if (obj instanceof Integer)
                    cell.setCellValue((Integer) obj);

            }

        }
    }

    //Write TakeOrderDetail
    for (String key : keyset) {
        for (int i = 0; i < data.get(key).size(); i++) {
            Row row = sheet.createRow(i + takeOrdersList.size() + 4);
            int cellnum = 0;
            for (Object obj : data.get(key).get(i).toArray()) {
                Cell cell = row.createCell(cellnum++);

                if (obj instanceof Timestamp)
                    cell.setCellValue((Timestamp) obj);
                else if (obj instanceof Boolean)
                    cell.setCellValue((Boolean) obj);
                else if (obj instanceof String)
                    cell.setCellValue((String) obj);
                else if (obj instanceof Float)
                    cell.setCellValue((Float) obj);
                else if (obj instanceof Integer)
                    cell.setCellValue((Integer) obj);

            }

        }
    }

    //Write to xls
    try {
        FileOutputStream output = new FileOutputStream(new File(fileInput + "\\test.xls"));

        workBook.write(output);
        output.close();
        System.out.println("Excel written successfully..");
        orderFile = new FileInputStream(new File(fileInput + "\\test.xls"));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return SUCCESS;
}

From source file:com.hp.action.TimeKeeperAction.java

public String exportExcel() {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();

    user = (User) session.getAttribute("USER");

    //Authorize//w  w  w.java2s .co  m
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    //GET DATA
    timeKeeperList = (List<TimeKeeper>) session.getAttribute("timeKeeperList");

    if (timeKeeperList == null)
        return INPUT;

    String fileInput = ServletActionContext.getServletContext().getRealPath("/db_exports/");
    String start = (String) session.getAttribute("startDate");
    String end = (String) session.getAttribute("endDate");

    //
    //Write
    HSSFWorkbook workBook = new HSSFWorkbook();
    HSSFSheet sheet = workBook.createSheet("Chm cng");
    //sheet.autoSizeColumn(200);
    sheet.setColumnWidth(0, 1000);
    sheet.setDefaultColumnWidth(20);

    //TakeOrder title
    for (int i = 1; i < 2; i++) {
        //
        Row rowstart = sheet.createRow(0);

        //Row Title
        Row row0 = sheet.createRow(i);
        row0.setHeight((short) 500);
        Cell cell0 = row0.createCell(0);

        //Merge for title
        sheet.addMergedRegion(new CellRangeAddress(i, //first row (0-based)
                i, //last row  (0-based)
                0, //first column (0-based)
                5 //last column  (0-based)
        ));
        //CellUtil.setAlignment(cell0, workBook, CellStyle.ALIGN_CENTER);
        CellStyle cellStyle = workBook.createCellStyle();
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);

        //font
        Font headerFont = workBook.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setFontHeight((short) 250);
        cellStyle.setFont(headerFont);

        cell0.setCellStyle(cellStyle);
        cell0.setCellValue("Bo co chm cng");

        //Row date
        Row row1 = sheet.createRow(i + 1);
        //row1.setHeight((short)500);
        Cell cell1 = row1.createCell(0);

        //Merge for title
        sheet.addMergedRegion(new CellRangeAddress(i + 1, //first row (0-based)
                i + 1, //last row  (0-based)
                0, //first column (0-based)
                5 //last column  (0-based)
        ));
        CellStyle cellAlign = workBook.createCellStyle();
        cellAlign.setAlignment(CellStyle.ALIGN_CENTER);
        cell1.setCellStyle(cellAlign);

        if (start == null)
            start = "";
        if (end == null)
            end = "";
        cell1.setCellValue("T ngy: " + start + " - ?n ngy: " + end);

        //Row Header
        Row row = sheet.createRow(4);
        int cellnum = 0;

        for (Object obj : titleArray()) {
            Cell cell = row.createCell(cellnum++);

            CellStyle style = workBook.createCellStyle();
            style.setFillForegroundColor(HSSFColor.YELLOW.index);
            style.setFillPattern(CellStyle.SOLID_FOREGROUND);

            cell.setCellStyle(style);

            if (obj instanceof Timestamp)
                cell.setCellValue((Timestamp) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Float)
                cell.setCellValue((Float) obj);
        }

    }
    //Write TakeOrder
    for (int i = 0; i < timeKeeperList.size(); i++) {
        Row row = sheet.createRow(i + 5);
        int cellnum = 0;

        //Cell 0 - stt
        Cell cell0 = row.createCell(cellnum++);
        cell0.setCellValue(i + 1);

        //Set content
        for (Object obj : objectArray(timeKeeperList.get(i))) {
            Cell cell = row.createCell(cellnum++);

            if (obj instanceof Timestamp)
                cell.setCellValue((Timestamp) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof Integer)
                cell.setCellValue((Integer) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Float) {

                //                    CellStyle cellStyle = workBook.createCellStyle();
                //                    DataFormat format = workBook.createDataFormat();
                //                    cellStyle.setDataFormat(format.getFormat("#.#"));
                //                    cell.setCellStyle(cellStyle);

                cell.setCellValue((Float) obj);
            } else if (obj instanceof Double)
                cell.setCellValue((Double) obj);
        }

    }

    outputFile = "BaoCaoChamCong" + start + " - " + end + ".xls";
    try {
        FileOutputStream output = new FileOutputStream(new File(fileInput + "\\" + outputFile));

        workBook.write(output);
        output.close();
        System.out.println("Excel written successfully..");
        orderFile = new FileInputStream(new File(fileInput + "\\" + outputFile));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return SUCCESS;
}

From source file:com.hp.idc.common.upload.JSONToExcelServlet.java

License:Open Source License

private void writeHead(JSONObject heads, Row row, int col) {
    if ((heads == null) || (heads.length() == 0))
        return;/* www .  java2  s . c  o  m*/
    try {
        String value = heads.optString("name");
        row.createCell(col).setCellValue(value);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.hp.idc.common.upload.JSONToExcelServlet.java

License:Open Source License

private void writeValue(JSONArray names, JSONObject values, Sheet sheet, int row) {
    if ((names == null) || (names.length() == 0))
        names = values.names();/*from  w w  w .  ja v  a2s .c  o m*/
    Row _row = sheet.createRow(row);
    try {
        for (int j = 0; j < names.length(); j++) {
            String value = values.optString(names.getString(j));
            _row.createCell(j).setCellValue(value);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.hp.idc.resm.util.ExcelUtil.java

License:Open Source License

/**
 * Excel/* w ww.  ja va  2  s.co  m*/
 * 
 * @param id
 *            ID
 * @return Excel
 */
public String getModelExcel(String id) {
    List<ModelAttribute> list = ServiceManager.getModelService().getModelAttributesByModelId(id);

    // 
    String[] IGNORATTR = new String[] { "id", "create_time", "contract_start", "searchcode", "last_update_time",
            "contract_end", "task_link", "order_id", "customer_id", "status", "last_update_by" };
    List<String> l = new ArrayList<String>(Arrays.asList(IGNORATTR));

    Workbook wb = new HSSFWorkbook();
    // Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet(id);
    CellStyle style = wb.createCellStyle();
    Font font = wb.createFont();
    font.setColor(HSSFColor.RED.index);
    style.setFont(font);
    // Create a row and put some cells in it. Rows are 0 based.
    Row row = sheet.createRow((short) 0);
    int i = 0;
    Cell cell = null;
    HSSFRichTextString textString;
    for (ModelAttribute ma : list) {
        if (l.contains(ma.getAttrId()))
            continue;
        cell = row.createCell(i);
        textString = new HSSFRichTextString(ma.getName() + "/" + ma.getAttrId());
        cell.setCellValue(textString);
        if (!ma.isNullable())
            cell.setCellStyle(style);
        sheet.autoSizeColumn(i);
        i++;
    }
    for (int k = 0; k < list.size(); k++) {
        sheet.autoSizeColumn(k);
    }
    // Write the output to a file
    FileOutputStream fileOut;
    String file;
    try {
        file = System.getProperty("user.dir") + "/../temp/" + id + new Random().nextLong() + ".xls";
        fileOut = new FileOutputStream(file);
        wb.write(fileOut);
        fileOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return "";
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    return file;
}

From source file:com.hp.idc.resm.util.ExcelUtil.java

License:Open Source License

/**
 * , Excel//from   w  ww .java2  s .  c  om
 * 
 * @param modelId
 *            Id
 * @return Excel
 */
public String getResouceDataToExcel(String modelId) {
    Model m = ServiceManager.getModelService().getModelById(modelId);

    List<ResourceObject> l = ServiceManager.getResourceService().getResourcesByModelId(modelId, 1);

    List<ModelAttribute> mas = m.getAttributes();
    Workbook wb = new HSSFWorkbook();
    CellStyle style = wb.createCellStyle();
    Font font = wb.createFont();
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    font.setFontHeightInPoints((short) 12);
    font.setFontName("");
    style.setFont(font);
    Sheet sheet = wb.createSheet(modelId);
    Row row = sheet.createRow(0);
    int i = 0;
    HSSFRichTextString textString;
    for (ModelAttribute ma : mas) {
        Cell cell = row.createCell(i);
        textString = new HSSFRichTextString(ma.getDefine().getName());
        cell.setCellStyle(style);
        cell.setCellValue(textString);
        i++;
    }
    i = 1;
    for (ResourceObject ro : l) {
        row = sheet.createRow(i);
        int j = 0;
        for (ModelAttribute ma : mas) {
            textString = new HSSFRichTextString(ro.getAttributeValue(ma.getAttrId()));
            row.createCell(j).setCellValue(textString);
            j++;
        }
        i++;
    }

    for (int k = 0; k < mas.size(); k++) {
        sheet.autoSizeColumn(k);
    }

    // Write the output to a file
    FileOutputStream fileOut;
    String file;
    try {
        file = System.getProperty("user.dir") + "/../temp/" + modelId + new Random().nextLong() + "_data.xls";
        fileOut = new FileOutputStream(file);
        wb.write(fileOut);
        fileOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return "";
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
    return file;
}

From source file:com.hris.payroll.thirteenthmonth.ExportDataGridToExcel.java

public void workSheet() {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Sample sheet");

    int rownum = 1;
    for (Object itemId : getDataGrid().getContainerDataSource().getItemIds()) {
        System.out.println("itemId: " + itemId);
    }/*  w  ww . ja  va2s . com*/
    for (Object itemId : getDataGrid().getContainerDataSource().getItemIds()) {
        Row row = sheet.createRow(rownum);
        int cellcount = 0;
        if ((rownum - 1) == 0) {
            Row rowHeader = sheet.createRow(rownum - 1);
            for (Object propertyId : getDataGrid().getContainerDataSource().getContainerPropertyIds()) {
                Cell cell = rowHeader.createCell(cellcount);
                if (propertyId.toString().contains("salary")) {
                    if (!propertyId.toString().equals("salary grand total")) {
                        cell.setCellValue(propertyId.toString().replace("salary", "").toUpperCase());
                    } else {
                        cell.setCellValue(propertyId.toString().toUpperCase());
                    }
                } else if (propertyId.toString().contains("tax")) {
                    if (!propertyId.toString().equals("tax grand total")) {
                        cell.setCellValue(propertyId.toString().replace("tax", "").toUpperCase());
                    } else {
                        cell.setCellValue(propertyId.toString().toUpperCase());
                    }
                } else if (propertyId.toString().contains("sss")) {
                    if (!propertyId.toString().equals("sss grand total")) {
                        cell.setCellValue(propertyId.toString().replace("sss", "").toUpperCase());
                    } else {
                        cell.setCellValue(propertyId.toString().toUpperCase());
                    }
                } else if (propertyId.toString().contains("phic")) {
                    if (!propertyId.toString().equals("phic grand total")) {
                        cell.setCellValue(propertyId.toString().replace("phic", "").toUpperCase());
                    } else {
                        cell.setCellValue(propertyId.toString().toUpperCase());
                    }
                } else if (propertyId.toString().contains("hdmf")) {
                    if (!propertyId.toString().equals("hdmf grand total")) {
                        cell.setCellValue(propertyId.toString().replace("hdmf", "").toUpperCase());
                    } else {
                        cell.setCellValue(propertyId.toString().toUpperCase());
                    }
                }

                else {
                    cell.setCellValue(propertyId.toString().toUpperCase());
                }

                sheet.autoSizeColumn(cellcount);
                cellcount++;
            }
        }

        Item item = getDataGrid().getContainerDataSource().getItem(itemId);
        int cellnum = 0;
        for (Object propertyId : item.getItemPropertyIds()) {
            Cell cell = row.createCell(cellnum);
            if (propertyId.equals("employee")) {
                cell.setCellValue(item.getItemProperty(propertyId).getValue().toString().toUpperCase());
            } else {
                cell.setCellValue((item.getItemProperty(propertyId).getValue() == null) ? " "
                        : item.getItemProperty(propertyId).getValue().toString());
            }

            sheet.autoSizeColumn(cellnum);
            cellnum++;
        }
        rownum++;
    }

    FileOutputStream fos;
    try {
        Date date = new Date();
        path = "C:/payroll-files/format-" + date.getTime() + ".xls";
        file = new File(path);
        fos = new FileOutputStream(path);
        workbook.write(fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException ex) {
        ErrorLoggedNotification.showErrorLoggedOnWindow(ex.toString(), this.getClass().getName());
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        ErrorLoggedNotification.showErrorLoggedOnWindow(ex.toString(), this.getClass().getName());
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }

    StreamResource.StreamSource source = () -> {
        try {
            File f = new File(path);
            FileInputStream fis = new FileInputStream(f);
            return fis;
        } catch (Exception e) {
            e.getMessage();
            return null;
        }
    };

    StreamResource resource = new StreamResource(source, "ThirteenthMonth.xls");
    resource.setMIMEType("application/vnd.ms-office");

}

From source file:com.huawei.gsm.util.response.SiteExcelBuilder.java

@Override
protected void buildExcelDocument(Map<String, Object> map, HSSFWorkbook hssfw, HttpServletRequest hsr,
        HttpServletResponse hsr1) throws Exception {

    List<SiteExcelWrapper> data = (List<SiteExcelWrapper>) map.get("exportData");

    HSSFSheet sheet = hssfw.createSheet("SITES");
    int rowSize = data.size() + 1;
    int columnSize = 9;
    String[] columns = new String[] { "Site ID", "Site Name", "Address", "latitude", "longitude", "Site Group",
            "Cell Index", "Cell Name", "Frequency" };

    Row headerRow = sheet.createRow(0);

    for (int i = 0; i < columns.length; i++) {
        String column = columns[i];
        headerRow.createCell(i).setCellValue(column);
    }//w  w w  .  j  a  va  2  s. c  o  m

    for (int i = 1; i <= data.size(); i++) {
        Row row = sheet.createRow(i);
        row.createCell(0).setCellValue(data.get((i - 1)).getSiteId());
        row.createCell(1).setCellValue(data.get((i - 1)).getSiteName());
        row.createCell(2).setCellValue(data.get((i - 1)).getAddress());
        row.createCell(3).setCellValue(data.get((i - 1)).getLatitute());
        row.createCell(4).setCellValue(data.get((i - 1)).getLongitude());
        row.createCell(5).setCellValue(data.get((i - 1)).getSiteGroup());
        row.createCell(6).setCellValue(data.get((i - 1)).getCellIndex());
        row.createCell(7).setCellValue(data.get((i - 1)).getCellName());
        row.createCell(8).setCellValue(data.get((i - 1)).getFrequency());
    }

}