Example usage for org.apache.poi.xssf.usermodel XSSFCell setCellValue

List of usage examples for org.apache.poi.xssf.usermodel XSSFCell setCellValue

Introduction

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

Prototype

@Override
public void setCellValue(boolean value) 

Source Link

Document

Set a boolean value for the cell

Usage

From source file:Import.Utils.XSSFConvert.java

/**
 * @param oldCell/*w  w  w.j  av a 2s  . c  o  m*/
 * @param newCell
 * @param styleMap
 */
public static void copyCell(HSSFCell oldCell, XSSFCell newCell, Map<Integer, HSSFCellStyle> styleMap) {
    if (styleMap != null) {
        int stHashCode = oldCell.getCellStyle().hashCode();
        HSSFCellStyle sourceCellStyle = styleMap.get(stHashCode);
        XSSFCellStyle destnCellStyle = newCell.getCellStyle();
        if (sourceCellStyle == null) {
            sourceCellStyle = oldCell.getSheet().getWorkbook().createCellStyle();
        }
        destnCellStyle.cloneStyleFrom(oldCell.getCellStyle());
        styleMap.put(stHashCode, sourceCellStyle);
        newCell.setCellStyle(destnCellStyle);
    }
    switch (oldCell.getCellType()) {
    case HSSFCell.CELL_TYPE_STRING:
        newCell.setCellValue(oldCell.getStringCellValue());
        break;
    case HSSFCell.CELL_TYPE_NUMERIC:
        newCell.setCellValue(oldCell.getNumericCellValue());
        break;
    case HSSFCell.CELL_TYPE_BLANK:
        newCell.setCellType(HSSFCell.CELL_TYPE_BLANK);
        break;
    case HSSFCell.CELL_TYPE_BOOLEAN:
        newCell.setCellValue(oldCell.getBooleanCellValue());
        break;
    case HSSFCell.CELL_TYPE_ERROR:
        newCell.setCellErrorValue(oldCell.getErrorCellValue());
        break;
    case HSSFCell.CELL_TYPE_FORMULA:
        newCell.setCellFormula(oldCell.getCellFormula());
        break;
    default:
        break;
    }

}

From source file:jpgtoxlsx.JPGtoXLSX.java

/**
 * @param args the command line arguments
 *///from   www. j  a  v a 2  s  . c om
public static void main(String[] args) throws Exception {

    XSSFWorkbook myExcel = new XSSFWorkbook();
    XSSFSheet sheet = myExcel.createSheet("Image");

    BufferedImage image = null;

    int width, height;
    int xlrows;
    //int pixel;

    File fimg;
    //open image
    try {
        fimg = new File("C:\\excel\\Test.jpg");
        image = ImageIO.read(fimg);
    } catch (IOException e) {
        System.out.println(e);
    }

    width = image.getWidth();
    //System.out.println(width);
    height = image.getHeight();
    //System.out.println(height);

    xlrows = height * 3;

    //System.out.println(pixel);

    int r, g, b;

    int w = image.getWidth();
    int h = image.getHeight();
    System.out.println("Width: " + w + "Height: " + h);
    System.out.println("Generating RGB values..");

    XSSFCellStyle style1 = myExcel.createCellStyle();
    XSSFCellStyle style2 = myExcel.createCellStyle();
    XSSFCellStyle style3 = myExcel.createCellStyle();

    for (int i = 1; i < ++h; i++) {

        if (i == image.getHeight()) {
            break;
        }

        XSSFRow row1 = sheet.createRow((i * 3 - 3));
        XSSFRow row2 = sheet.createRow((i * 3 - 2));
        XSSFRow row3 = sheet.createRow((i * 3 - 1));

        for (int j = 0; j < ++w; j++) {

            if (j == image.getWidth()) {
                break;
            }

            //System.out.println("I: " + i);
            //System.out.println("J: " + j + "\n");
            int x = i;
            int y = j;

            //System.out.println("X: " + x + "Y: " + y + "\r");
            //System.out.println("Y: " + y);
            int pixel = image.getRGB(y, x);
            r = (pixel >> 16) & 0xff;
            g = (pixel >> 8) & 0xff;
            b = (pixel) & 0xff;

            XSSFCell cell1 = row1.createCell(y);
            XSSFCell cell2 = row2.createCell(y);
            XSSFCell cell3 = row3.createCell(y);

            cell1.setCellValue(Integer.toString(r));
            cell2.setCellValue(Integer.toString(g));
            cell3.setCellValue(Integer.toString(b));

            style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(r, 0, 0)));
            ;
            style1.setFillPattern(CellStyle.SOLID_FOREGROUND);

            style2.setFillForegroundColor(new XSSFColor(new java.awt.Color(0, g, 0)));
            style2.setFillPattern(CellStyle.SOLID_FOREGROUND);

            style3.setFillForegroundColor(new XSSFColor(new java.awt.Color(0, 0, b)));
            style3.setFillPattern(CellStyle.SOLID_FOREGROUND);

            cell1.setCellStyle(style1);
            cell2.setCellStyle(style2);
            cell3.setCellStyle(style3);

            //System.out.println("x,y: " + j + ", " + i);
            //System.out.println("R: " + r + " G: " + g + " B: " + b + "\n");
        }
    }
    System.out.println("RGB values extracted.");
    System.out.println("Generating image");

    myExcel.write(new FileOutputStream("excel.xlsx"));
    myExcel.close();

}

From source file:ke.co.tawi.babblesms.server.servlet.export.excel.inbox.ExportExcel.java

License:Open Source License

/**
 * Returns MS Excel file of the data specified for exporting.
 * @param List<IncomingLog>//from ww  w.  j a  v  a  2  s.c  om
 * Method create excelSheets and sends them
 ****/
public void createExcelSheets(List<IncomingLog> InLog) throws IOException {
    List<Phone> phoneList;
    //String cont = null;

    XSSFWorkbook xf = new XSSFWorkbook();
    XSSFCreationHelper ch = xf.getCreationHelper();

    XSSFSheet s = xf.createSheet();
    //create the first row
    XSSFRow r1 = s.createRow(0);
    XSSFCell c11 = r1.createCell(0);
    c11.setCellValue(ch.createRichTextString("*"));
    XSSFCell c12 = r1.createCell(1);
    c12.setCellValue(ch.createRichTextString("Message"));
    XSSFCell c13 = r1.createCell(2);
    c13.setCellValue(ch.createRichTextString("Source"));
    XSSFCell c14 = r1.createCell(3);
    c14.setCellValue(ch.createRichTextString("Destination"));
    XSSFCell c15 = r1.createCell(4);
    c15.setCellValue(ch.createRichTextString("Network"));
    XSSFCell c16 = r1.createCell(5);
    c16.setCellValue(ch.createRichTextString("Time (" + timezoneFormatter.format(new Date()) + ") Time Zone"));
    XSSFCell c17 = r1.createCell(6);
    c17.setCellValue(ch.createRichTextString("Message Id"));

    int i = 1;
    //create other rows
    for (IncomingLog log : InLog) {
        phoneList = phnDAO.getPhones(log.getOrigin());

        XSSFRow r = s.createRow(i);
        //row number
        XSSFCell c1 = r.createCell(0);
        c1.setCellValue(i + pageno);

        //get message  
        XSSFCell c2 = r.createCell(1);
        c2.setCellValue(ch.createRichTextString(log.getMessage()));

        //get phone numbers
        XSSFCell c3 = r.createCell(2);
        if (phoneList.size() > 0) {
            for (Phone phone : phoneList) {
                Contact contacts = ctDAO.getContact(phone.getContactUuid());
                c3.setCellValue(ch.createRichTextString(contacts.getName()));
            }
        } else {
            c3.setCellValue(ch.createRichTextString(log.getOrigin()));
        }

        //get destination   
        XSSFCell c4 = r.createCell(3);
        c4.setCellValue(ch.createRichTextString(log.getDestination()));

        //get network name    
        XSSFCell c5 = r.createCell(4);
        c5.setCellValue(ch.createRichTextString(networkHash.get(log.getNetworkUuid())));

        //get date 
        XSSFCell c6 = r.createCell(5);
        c6.setCellValue(ch.createRichTextString("" + dateFormatter.format(log.getLogTime())));

        //get message id
        XSSFCell c7 = r.createCell(6);
        c7.setCellValue(ch.createRichTextString(log.getUuid()));
        i++;

    }
    xf.write(out);
    out.flush();
    out.close();
}

From source file:kp.servlet.ExportRpt.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w w  .java2  s.com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    Logger.getLogger(ExportRpt.class.getName()).log(Level.SEVERE,
            "accRole :" + request.getParameter("accRole"));
    Logger.getLogger(ExportRpt.class.getName()).log(Level.SEVERE, "Unit :" + request.getParameter("unit"));
    ArrayList<MocWfTran> Mocstatus = new ArrayList<>();
    TranDao tdao = new TranDao();
    Mocstatus = tdao.getMocStatusList(request.getParameter("accRole"), request.getParameter("unit"),
            request.getParameter("user"));

    //Developing Metadata
    String rptName = "MOC Status Excel Report";
    ArrayList<String> colLabel = new ArrayList<>();
    colLabel.add("Case Id");
    colLabel.add("Moc NO");
    colLabel.add("Moc Title");
    colLabel.add("Moc Status");
    colLabel.add("Creation Date");
    colLabel.add("Owner's Name");
    colLabel.add("Unit");
    colLabel.add("Plant");
    colLabel.add("Current Stage");
    colLabel.add("Pending At");

    //Starting EXCEL Creating
    //XLS Variable
    XSSFSheet spreadsheet;
    XSSFWorkbook workbook;
    XSSFRow row;
    XSSFCell cell;
    XSSFFont xfont = null;
    XSSFCellStyle xstyle = null;

    //2.Create WorkBook and Sheet
    workbook = new XSSFWorkbook();
    spreadsheet = workbook.createSheet(rptName);

    //set header style
    xfont = workbook.createFont();
    xfont.setFontHeight(11);
    xfont.setFontName("Calibri");
    xfont.setBold(true);

    //Set font into style
    CellStyle borderStyle = workbook.createCellStyle();
    borderStyle.setAlignment(CellStyle.ALIGN_CENTER);
    borderStyle.setFont(xfont);
    xstyle = workbook.createCellStyle();
    xstyle.setFont(xfont);

    //header
    row = spreadsheet.createRow(0);
    cell = row.createCell(0);
    cell.setCellValue(rptName);
    cell.setCellStyle(borderStyle);
    spreadsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, colLabel.size() - 1));

    //3.Get First Row and Set Headers
    row = spreadsheet.createRow(1);

    for (int i = 0; i < colLabel.size(); i++) {
        cell = row.createCell(i);
        cell.setCellValue(colLabel.get(i));
        cell.setCellStyle(xstyle);
    }

    //Itrate or Database data and write
    int i = 2;
    for (MocWfTran bean : Mocstatus) {
        row = spreadsheet.createRow(i);
        cell = row.createCell(0);
        cell.setCellValue(bean.getCaseId());
        cell = row.createCell(1);
        cell.setCellValue(bean.getMocNo());
        cell = row.createCell(2);
        cell.setCellValue(bean.getCaseName());
        cell = row.createCell(3);
        cell.setCellValue(bean.getMocStatus());
        cell = row.createCell(4);
        cell.setCellValue(bean.getCrDateString());
        cell = row.createCell(5);
        cell.setCellValue(bean.getCaseOwnerName());
        cell = row.createCell(6);
        cell.setCellValue(bean.getUnitId());
        cell = row.createCell(7);
        cell.setCellValue(bean.getPlantId());
        cell = row.createCell(8);
        cell.setCellValue(bean.getStgNname());
        cell = row.createCell(9);
        cell.setCellValue(bean.getUserNname());
        i++;
    }

    //Export to Excel
    String file_name = "MocStatus";
    String path = getServletContext().getRealPath("/");
    String full_path = path + "/report/" + file_name + ".xlsx";
    //        FileOutputStream out = new FileOutputStream(new File("D://" + file_name + ".xlsx"));
    FileOutputStream out = new FileOutputStream(new File(full_path));
    workbook.write(out);

    //Download code 
    // reads input file from an absolute path
    File downloadFile = new File(full_path);
    OutputStream outStream;
    // obtains ServletContext
    try (FileInputStream inStream = new FileInputStream(downloadFile)) {
        //obtains ServletContext
        ServletContext context = getServletContext();
        // gets MIME type of the file
        String mimeType = context.getMimeType(full_path);
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        } // modifies response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());
        // forces download
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
        response.setHeader(headerKey, headerValue);
        // obtains response's output stream
        outStream = response.getOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }
    }
    outStream.close();
    //        response.sendRedirect("mocstatus.jsp");
}

From source file:localization.excel.java

public static void convert(String filePath) {
    Vector<String> zFile;
    if (filePath.endsWith(".zip")) {
        zFile = readzipfile(filePath);/*from   w  w w . j a va2  s  .  c  o  m*/
        for (String s : zFile) {
            if (s.endsWith(".xlsx")) {
                //System.out.println(s);
                convert(s);
            }
        }
    } else if (!filePath.endsWith(".xlsx")) {
        return;
    } else {
        try {
            FileInputStream file = new FileInputStream(new File(filePath));
            System.out.println(filePath);
            //Get the workbook instance for XLS file 
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            XSSFSheet sheet = workbook.getSheetAt(0);
            XSSFRow row;
            XSSFCell cell;
            rowNumber = sheet.getPhysicalNumberOfRows();
            try {
                for (int i = 0; i < rowNumber; i++) {
                    row = sheet.getRow(i);
                    if (row != null) {
                        int columnNum = row.getPhysicalNumberOfCells();
                        //System.out.println(columnNum);
                        for (int j = 0; j < columnNum; j++) {
                            cell = row.getCell(j);

                            if (j == 0) {
                                String name = cell.getRichStringCellValue().getString();
                                if (name.equalsIgnoreCase("Esri")) {
                                    langNumber++;
                                }
                                //System.out.println(name);
                            }
                        }
                        if (i == 3) {
                            cell = row.getCell(30);
                            XSSFCellStyle cs = cell.getCellStyle();
                            cell = row.createCell(32);
                            cell.setCellValue("Additional Charge per language");
                            cell.setCellStyle(cs);
                        }
                    }
                }
            } catch (Exception e) {

            }
            System.out.println(langNumber);
            double total = Double.parseDouble(sheet.getRow(langNumber + 3).getCell(29).getRawValue());

            double subTotal = total / langNumber;
            DecimalFormat df = new DecimalFormat("#.000");
            for (int i = 0; i < langNumber; i++) {
                cell = sheet.getRow(i + 4).createCell(32);
                cell.setCellValue("$" + df.format(subTotal));
            }

            file.close();
            FileOutputStream outFile = new FileOutputStream(filePath);
            workbook.write(outFile);
            outFile.close();
            rowNumber = 0;
            langNumber = 0;
            System.out.println("Done");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:Logic.RStoXL.java

public void genXLS(ResultSet rs, String Rpt_name, String path) {
    try {//from   w w  w.  j  av  a2  s.co m
        //RS METE DATA
        ResultSetMetaData rsmd = rs.getMetaData();
        int col_count = rsmd.getColumnCount();
        ArrayList<String> col_name = new ArrayList<String>();
        for (int i = 1; i <= col_count; i++) {
            col_name.add(rsmd.getColumnLabel(i));
        }

        //XLS Variable
        XSSFSheet spreadsheet;
        XSSFWorkbook workbook;
        XSSFRow row;
        XSSFCell cell;
        XSSFFont xfont = null;
        XSSFCellStyle xstyle = null;

        //2.Create WorkBook and Sheet
        workbook = new XSSFWorkbook();
        spreadsheet = workbook.createSheet(Rpt_name);

        //set header style
        xfont = workbook.createFont();
        xfont.setFontHeight(11);
        xfont.setFontName("Calibri");
        xfont.setBold(true);

        //Set font into style
        CellStyle borderStyle = workbook.createCellStyle();
        borderStyle.setAlignment(CellStyle.ALIGN_CENTER);
        borderStyle.setFont(xfont);
        xstyle = workbook.createCellStyle();
        xstyle.setFont(xfont);

        //header
        row = spreadsheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue(Rpt_name);
        cell.setCellStyle(borderStyle);
        spreadsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, col_count - 1));

        //3.Get First Row and Set Headers
        row = spreadsheet.createRow(1);

        for (int i = 0; i < col_count; i++) {
            cell = row.createCell(i);
            cell.setCellValue(col_name.get(i));
            cell.setCellStyle(xstyle);
        }

        //Itrate or Database data and write
        int i = 2;
        while (rs.next()) {
            row = spreadsheet.createRow(i);
            for (int j = 1; j <= col_count; j++) {
                cell = row.createCell(j - 1);
                cell.setCellValue(rs.getString(j));
            }
            i++;
        }

        //Export to Excel
        // FileOutputStream out = new FileOutputStream(new File("D://" + Rpt_name + ".xlsx"));
        FileOutputStream out = new FileOutputStream(new File(path));
        workbook.write(out);

        Logger.getLogger(RStoXL.class.getName()).log(Level.SEVERE, "DONE|!");
        Logger.getLogger(RStoXL.class.getName()).log(Level.SEVERE, "");
    } catch (SQLException ex) {
        Logger.getLogger(RStoXL.class.getName()).log(Level.SEVERE, "Exception : {0}", ex);
    } catch (IOException ex) {
        Logger.getLogger(RStoXL.class.getName()).log(Level.SEVERE, "Exception : {0}", ex);
    }
}

From source file:Logic.Xls.java

public void genXLS(ResultSet rs, String Rpt_name, String path) {
    try {//w  w  w  .  j  a  v a  2  s  . c  o m
        //RS METE DATA
        ResultSetMetaData rsmd = rs.getMetaData();
        int col_count = rsmd.getColumnCount();
        ArrayList<String> col_name = new ArrayList<>();
        for (int i = 1; i <= col_count; i++) {
            col_name.add(rsmd.getColumnLabel(i));
        }

        //XLS Variable
        XSSFSheet spreadsheet;
        XSSFWorkbook workbook;
        XSSFRow row;
        XSSFCell cell;
        XSSFFont xfont = null;
        XSSFCellStyle xstyle = null;

        //2.Create WorkBook and Sheet
        workbook = new XSSFWorkbook();
        spreadsheet = workbook.createSheet(Rpt_name);

        //set header style
        xfont = workbook.createFont();
        xfont.setFontHeight(11);
        xfont.setFontName("Calibri");
        xfont.setBold(true);

        //Set font into style
        CellStyle borderStyle = workbook.createCellStyle();
        borderStyle.setAlignment(CellStyle.ALIGN_CENTER);
        borderStyle.setFont(xfont);
        xstyle = workbook.createCellStyle();
        xstyle.setFont(xfont);

        //header
        row = spreadsheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue(Rpt_name);
        cell.setCellStyle(borderStyle);
        spreadsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, col_count - 1));

        //3.Get First Row and Set Headers
        row = spreadsheet.createRow(1);

        for (int i = 0; i < col_count; i++) {
            cell = row.createCell(i);
            cell.setCellValue(col_name.get(i));
            cell.setCellStyle(xstyle);
        }

        //Itrate or Database data and write
        int i = 2;
        while (rs.next()) {
            row = spreadsheet.createRow(i);
            for (int j = 1; j <= col_count; j++) {
                cell = row.createCell(j - 1);
                cell.setCellValue(rs.getString(j));
            }
            i++;
        }

        //Export to Excel
        // FileOutputStream out = new FileOutputStream(new File("D://" + Rpt_name + ".xlsx"));
        FileOutputStream out = new FileOutputStream(new File(path));
        workbook.write(out);

        Logger.getLogger(Xls.class.getName()).log(Level.SEVERE, "DONE|!");
        Logger.getLogger(Xls.class.getName()).log(Level.SEVERE, "");
    } catch (Exception ex) {
        Logger.getLogger(Xls.class.getName()).log(Level.SEVERE, "Exception : " + ex);
    }
}

From source file:Main.Database.java

/**
 * @param dbTable - the database table which contains job results from a
 * particular job board./*from w  w w  . ja  va  2  s  . co m*/
 * @param excelSheetIndex - the sheet index on the Excel File which will
 * house the results from the database.
 *
 * This method appends results from the specific database table onto the
 * index of the excel sheet.
 */
/*
 public void appendDBTableToExcel(String dbTable, int excelSheetIndex) {
 try {
 connect = connectDatabase();
 String sqlQuery = "Select *from " + dbTable;
 // create the java statement
 selectStmt = connect.prepareStatement(sqlQuery);
 resultSet = selectStmt.executeQuery();
 //call upon the excel file.
 excelFile = new File("C:\\Users\\jason\\Desktop\\Job Scraper\\JobScraper\\src\\main\\java\\Main\\links.xlsx");
 excelInputStream = new FileInputStream(excelFile);
 Workbook workbook = create(excelInputStream);
        
 CreationHelper createHelper = workbook.getCreationHelper();
 Sheet sheet = workbook.getSheetAt(excelSheetIndex);
 excelOutputStream = new FileOutputStream(excelFile);
 //set link style to blue
 CellStyle hlinkstyle = workbook.createCellStyle();
 Font hlinkfont = workbook.createFont();
 hlinkfont.setUnderline(XSSFFont.U_SINGLE);
 hlinkfont.setColor(HSSFColor.BLUE.index);
 hlinkstyle.setFont(hlinkfont);
        
 // iterate through the java database,grabbing the details of the job.
 System.out.println("I can see contents of database");
 while (resultSet.next()) {
 this.title = resultSet.getString("title");
 this.link = resultSet.getString("link");
 this.date = resultSet.getString("date");
 System.out.println(this.title + " / " + this.link + " / " + this.date );
 //append database Information onto Excel
 Row row = sheet.createRow(rowNumber);
 Cell titleCell = row.createCell(0);
 titleCell.setCellValue(title);
 Cell linkCell = row.createCell(1);
 linkCell.setCellValue(link);
 Cell dateCell = row.createCell(2);
 dateCell.setCellValue(date);
        
 //Make the link a clickable blue url.
 XSSFHyperlink hyperLink = (XSSFHyperlink) createHelper.createHyperlink(Hyperlink.LINK_URL);
 hyperLink.setAddress(link);
 linkCell.setHyperlink(hyperLink);
 linkCell.setCellStyle(hlinkstyle);
 rowNumber++;
 }
 //autosizes the columns for clarity
 for (int i = 0; i < 3; i+=2) {
 sheet.autoSizeColumn(i);
 }
 selectStmt.close();
 excelOutputStream = new FileOutputStream(excelFile);
 workbook.write(excelOutputStream);
 excelOutputStream.close();
            
            
 System.out.println("Printed out " + dbTable);
 } catch (SQLException ex) {
 getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
 } catch (FileNotFoundException ex) {
 getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
 } catch (IOException ex) {
 getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
 } catch (InvalidFormatException ex) {
 Logger.getLogger(IndeedScraper.class.getName()).log(Level.SEVERE, null, ex);
 }
 }
 */
public void appendDBTableToExcel(String dbTable) {
    rowNumber = 0;
    try {
        connect = connectDatabase();
        Statement statement = connect.createStatement();
        ResultSet resultSet = statement.executeQuery("Select * from " + dbTable);

        File file = new File("exceldatabase.xlsx");
        if (file.exists()) {
            closeDBSession();
            callExistingExcel(dbTable);
        } else {
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet spreadsheet = workbook.createSheet(dbTable);
            while (resultSet.next()) {
                XSSFRow row = spreadsheet.createRow(rowNumber);
                XSSFCell titleCell = row.createCell(0);
                titleCell.setCellValue(resultSet.getString("title"));
                XSSFCell linkCell = row.createCell(1);
                linkCell.setCellValue(resultSet.getString("link"));
                XSSFCell dateCell = row.createCell(2);
                dateCell.setCellValue(resultSet.getString("date"));
                System.out.println(resultSet.getString("title") + " / " + resultSet.getString("link")
                        + resultSet.getString("date"));
                rowNumber++;
            }
            //autosizes the columns for clarity
            for (int i = 0; i < 3; i += 2) {
                spreadsheet.autoSizeColumn(i);
            }
            FileOutputStream out = new FileOutputStream(new File("exceldatabase.xlsx"));
            workbook.write(out);
            out.close();
            System.out.println("exceldatabase.xlsx written successfully");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Main.Database.java

private void callExistingExcel(String dbTable) throws FileNotFoundException, IOException, SQLException {
    rowNumber = 0;// ww  w .  ja v a 2s.com
    connect = connectDatabase();
    Statement statement = connect.createStatement();
    ResultSet resultSet = statement.executeQuery("Select * from " + dbTable);

    File file = new File("exceldatabase.xlsx");
    FileInputStream fIP = new FileInputStream(file);
    //Get the workbook instance for XLSX file 
    XSSFWorkbook workbook = new XSSFWorkbook(fIP);
    try {
        if (file.isFile() && file.exists()) {
            System.out.println("openworkbook.xlsx file open successfully.");
            XSSFSheet spreadsheet = workbook.createSheet(dbTable);
            while (resultSet.next()) {
                XSSFRow row = spreadsheet.createRow(rowNumber);
                XSSFCell titleCell = row.createCell(0);
                titleCell.setCellValue(resultSet.getString("title"));
                XSSFCell linkCell = row.createCell(1);
                linkCell.setCellValue(resultSet.getString("link"));
                XSSFCell dateCell = row.createCell(2);
                dateCell.setCellValue(resultSet.getString("date"));
                System.out.println(resultSet.getString("title") + " / " + resultSet.getString("link")
                        + resultSet.getString("date"));
                rowNumber++;
            }
            //autosizes the columns for clarity
            for (int i = 0; i < 3; i += 2) {
                spreadsheet.autoSizeColumn(i);
            }
            FileOutputStream out = new FileOutputStream("exceldatabase.xlsx");
            workbook.write(out);
            out.close();
            System.out.println("Successfully written");
        } else {
            System.out.println("Error to open openworkbook.xlsx file.");
        }
    } catch (IllegalArgumentException ex) {
    }
}

From source file:minor.Bill.java

private void writetoexcel() {
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet ws = wb.createSheet();/*from www .jav  a  2 s  . c om*/

    //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) });

    }

    //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/bill.xlsx"));
        wb.write(fos);
        fos.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ex);
    }

}