skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Showing posts with label Excel Example. Show all posts
Showing posts with label Excel Example. Show all posts
Monday, October 29, 2012

Transferring macros using java

Posted by Raju Gupta at 1:59 AM – 0 comments
 

Macros of excel can be executed using vbscript calling from a java file

using apachepoi and jexcel api we can read and write in excel file using this jars but to read macros we need to run vb script and this method calls vbscript and transfer macros....or other way around use component to change excel file in to xml file and then load it to your project

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
 
public class AccessMacro {
 
    private static void createAndShowGUI(){
 
        JFrame frame1 = new JFrame("Run Macro");
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        JButton button = new JButton(" >> JavaProgrammingForums.com <<");
        // Add action listener to button
        button.addActionListener(new ActionListener() {
 
 
            public void actionPerformed(ActionEvent e) {
                // Execute when button is pressed
                try{
                Runtime.getRuntime().exec("cmd /c start runmacro.vbs");
                }catch(Exception a){
                    System.out.println("Problem opening runmacro script!");
                }
            }
        });
 
 
        frame1.getContentPane().add(button);
        frame1.pack();
        frame1.setVisible(true);
    }
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

[ Read More ]
Read more...
Saturday, October 27, 2012

Excel Data To Delimited File Utility

Posted by Raju Gupta at 7:30 PM – 0 comments
 

A windows based File converter utility has been developed (with Java) to convert an excel file into a delimited format.

This utility takes two inputs ,need to be provided by the user :
1) The path of the excel file (.xls/.xlt) required to be converted
2) Delimiter to be used (For example : pipe (|), comma (,), dollar ($) )

A delimited file named output_<worksheet>.txt is created ,on the same location as of input excel file. Also ,the utility is able to read multiple worksheets of the excel and the output file(s) should be opened with notepad.   

/*GetUserInput.java*/


import java.io.*;

public class GetUserInput
{  
 /*Method to take excel file path and name input from user*/
 String input()
 {
  System.out.print("Enter excel file name in the pattern C:\FolderName\filename " + "n");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String inputfile = null;
  try
  {
   inputfile = br.readLine();
  }catch (IOException e) 
   {         
   System.out.println("Error in input file!");        
   System.exit(1);      
   }
  return inputfile;
 }/*Method input closed*/
 
 /*Method to take delimiter to be used from user*/
 String delimiter()
 {
  System.out.print("Enter delimiter to be used " + "n");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String delimiter = null;
  try
  {
   delimiter = br.readLine();
  }catch (IOException e) 
  {         
   System.out.println("Error in delimiter!");        
   System.exit(1);      
  }
  return delimiter;
 }/*Method delimiter closed*/
}/*Class closed*/

/****************************************************************************************/
/*ConvertExcelToCSV.java*/

import java.io.*;
import jxl.*;
import java.util.*;
class  ConvertExcelToDelimited
{
 public static void main(String[] args)
 {
  try
  {
   /*To Get the input excel name from user*/
   GetUserInput input1 = new GetUserInput();
   String filename = null;
   filename = input1.input();
   
   /*To Get delimiter to be used from user*/
   GetUserInput input2 = new GetUserInput();
   String user_delimiter = null;
   user_delimiter= input2.delimiter();
   
   /*To Get the output file path from the input excel name*/ 
   File outpath = new File(filename);
   String outputpath = null;
   outputpath = outpath.getParent();
   

   WorkbookSettings ws = new WorkbookSettings();
   ws.setLocale(new Locale("en", "EN"));
   Workbook w = Workbook.getWorkbook(new File(filename),ws);
   
   for (int sheet = 0; sheet < w.getNumberOfSheets(); sheet++)
   {
    /*Objects :
     * 1. To read each sheet 
     * 2. Create output files as per the sheet name in the excel */
    Sheet s = w.getSheet(sheet);
    File f = new File(outputpath+"//output_" + s.getName() + ".txt");
    
    OutputStream os = (OutputStream)new FileOutputStream(f);
    String encoding = "UTF8";
    OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
    BufferedWriter bw = new BufferedWriter(osw);
    
    Cell[] row = null;
    for (int i = 0 ; i < s.getRows() ; i++)
    {
     row = s.getRow(i);
     if (row.length > 0)
     {
      bw.write(row[0].getContents());
      for (int j = 1; j < row.length; j++)
      {
       bw.write(user_delimiter);
       bw.write(row[j].getContents());
      }/*For loop closed*/
     }/*If closed*/         
     bw.newLine();
    }/*Row for loop closed*/
    bw.flush();
    bw.close();
    System.out.print("Output File " + (sheet+1) +  " is created: " + outputpath +"\output_"+ s.getName() +".txt" + "n" );
   }/*Worksheet for loop closed*/      
   System.out.print("Please open the output file(s) using notepad.");   
   
  }/*Try closed*/
  catch (Exception e)
  {
   System.err.println(e);
  }/*Catch closed*/
 }/*Main Closed*/
}/*Class closed*/

[ Read More ]
Read more...
Thursday, October 18, 2012

Read data from xslx using JAVA

Posted by Raju Gupta at 8:00 AM – 0 comments
 

Need to read data from excel sheet:

We can use Apache POI API, to access the Microsoft documents including Excel formats.
Refer below page for more information on XL API

http://poi.apache.org/spreadsheet/index.html

Need Apache POI jar files:
  • poi-3.1-FINAL-20080629.jar
  • poi-scratchpad-3.1-FINAL-20080629.jar
  • poi-contrib-3.1-FINAL-20080629.jar
  • poi-2.5.1-final-20080629.jar

If we need to read from from xslx then we have to use POI 3.7 version.

Here is the sample code:


if(upload.getContentType().equalIgnoreCase("application/vnd.ms-excel") ||
 ( upload.getContentType().equalIgnoreCase("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
{
 Vector cellVectHolder = new Vector();
 Iterator rowIter = null;
 try{
  Workbook wb = WorkbookFactory.create(upload.getInputStream);
  Sheet mySheet = wb.getSheetAt(0);
  rowIter = mySheet.rowIterator();
  while(rowIter.hasNext()){
   Row myRow = (Row) rowIter.next();
   Iterator cellIter = myRow.cellIterator();
   Vector cellStoreVect = new Vector();
   while(cellIter.hasNext()){
    Cell myCell = (Cell) cellIter.next();
    cellStoreVect.addElement(myCell);
   }
   cellVectHolder.addElement(cellStoreVect);
  }
  for(int i=0;i i<cellVectHolder.size();i++)
  {
   Vector cellStoreVect = (Vector)cellVectHolder.elementAt(i);
   for(int j=0; j<cellStoreVect.size();j++)
   {
    Cell myCell = (Cell) cellStoreVect.elementAt(j);
    String stringCellValue = mycell.toString();
    System.out.println("stringCellValue" +stringCellValue);
   }
    System.out.println();
  }
 }
 catch(Exception e)
 {
  e.printStackTrace();
 }

[ Read More ]
Read more...
Monday, October 15, 2012

Read contents of excel files with any format

Posted by Raju Gupta at 6:00 AM – 0 comments
 

The code snippet can be used to process excel files of any format.(xls or xlsx)

The code snippet can be used in areas where excel file of any format needs to be uploaded and processes.

The following jars will be needed to run the code snippet.
  1. xmlbeans-2.3.0.jar
  2. dom4j-1.1.jar
  3. poi-ooxml-schemas-3.6-20091214.jar
  4. poi-ooxml-3.6-20091214.jar
  5. poi-3.6-20091214.jar 


import org.apache.poi.xssf.usermodel.XSSFWorkbook; 
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import java.util.Iterator;
import java.io.*;
public class JavaApplication3 {


 public void ReadExcel2007Sheet(String filename) throws Exception
 {
  FileInputStream fis = null;
  try {
   fis = new FileInputStream(filename);

   XSSFWorkbook workbook = new XSSFWorkbook(fis);
   XSSFSheet sheet = workbook.getSheetAt(0);
   Iterator rows = sheet.rowIterator();
   int number=sheet.getLastRowNum();
   System.out.println(" number of rows"+ number);
   while (rows.hasNext())
   {

    XSSFRow row = ((XSSFRow) rows.next());
    Iterator cells = row.cellIterator();
    while(cells.hasNext())
    {
     XSSFCell cell = (XSSFCell) cells.next();
     String Value=cell.getStringCellValue();
     System.out.println(Value);
    }
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (fis != null) {
    fis.close();
   }
  }

 }
 public void readOtherExcel(String inputFile) throws IOException  {
  File inputWorkbook = new File(inputFile);
  Workbook w;
  try {
   w = Workbook.getWorkbook(inputWorkbook);
   // Get the first sheet
   Sheet sheet = w.getSheet(0);
   // Loop over columns and lines

   for (int j = 0; j < sheet.getColumns(); j++) {
    for (int i = 0; i < sheet.getRows(); i++) {
     Cell cell = sheet.getCell(j, i);
     CellType type = cell.getType();
     if (cell.getType() == CellType.LABEL) {
      System.out.println("It is a label "
        + cell.getContents());
     }

     if (cell.getType() == CellType.NUMBER) {
      System.out.println("It contains numbers"
        + cell.getContents());
     }

    }
   }
  } catch (BiffException e) {
   e.printStackTrace();
  }
 }
 public static void main(String[] args) {
  JavaApplication3 object=new JavaApplication3();
  String filename1 = "Excel2007.xlsx";

  int dotposition1= filename1.lastIndexOf(".");

  String ext1 = filename1.substring(dotposition1 + 1, filename1.length()); 

  if(ext1.equalsIgnoreCase("xlsx"))
  {

   try{
    object.ReadExcel2007Sheet(filename1);

   }catch(Exception e)
   {
    e.printStackTrace();
   } 
  }
  else if(ext1.equalsIgnoreCase("xls"))
  {
   try{
    object.readOtherExcel(filename1);

   }catch(Exception e)
   {
    e.printStackTrace();
   }  
  }


 }

}


[ Read More ]
Read more...
Sunday, October 14, 2012

Creating Dynamic Macro Enabled Excel by Java

Posted by Raju Gupta at 12:00 PM – 0 comments
 

We can create a dynamic macro enabled excel by java:
We need to create a excel sheet template with macro on server.
we can copy the macro in a new excel sheet and write the data in that excel sheet.
We can create a rule by which we can poluate the list in excel on the basis of previous selected cell value
For this we need a jar: POI 3.08  

/*
* class MacroEnabledExcelTemplateAction
*/

package com.tcs.reuse.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddressList;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.tcs.reuse.MacroEnabledExcelTemplateBus;


// TODO: Auto-generated Javadoc
/**
 * The Class MacroEnabledExcelTemplateAction.
 * 
 */
public class MacroEnabledExcelTemplateAction extends Action {

    /** The logger. */
    private static Logger logger = Logger
     .getLogger(com.tcs.reuse.action.MacroEnabledExcelTemplateAction.class);
    static String strHost = null;

    /**
     * Instantiates a new macro enabled excel template action.
     */
    public MacroEnabledExcelTemplateAction() {

  super();
  logger.debug("****In the constructor of MacroEnabledExcelTemplateAction**");
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.apache.struts.action.Action#execute(org.apache.struts.action.
     * ActionMapping, org.apache.struts.action.ActionForm,
     * javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse)
     */

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
     HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {

 logger.debug("ENTRY MacroEnabledExcelTemplateAction execute");
 /*
  * Variables declaration
  */
 HttpSession session = null;
 String userId = "";
 String tempPath = "";
 
 
 int newCellMainSheet = 0;
 int newRowMainSheet = 1;
 int totalNumberOfRows = 10;
 
 boolean existFolderAtServer = true;
 boolean deletedDir = false;

 ArrayList<String> errors = null;
 ArrayList<String> msg = null;
 final boolean hasAccess = true;

 InputStream inputFile = null;
 FileOutputStream outputFile = null;
 InputStream inputFile2 = null;
 File file = null;
 File existFile = null;

 DataValidationHelper dvHelper = null;
 DataValidationConstraint dvConstraint = null;
 DataValidation validation = null;
 CellRangeAddressList addressList = null;
 Row mainSheetRow = null;
 Cell mainSheetCell = null;
 HSSFCellStyle cs = null;
 HSSFCellStyle cs1 = null;
 HSSFCellStyle headerCS = null;
 HSSFCellStyle backgroundColor = null;
 HSSFFont font = null;
 HSSFFont font1 = null;
 HSSFFont headerFont = null;
 HSSFWorkbook wb = null;
 HSSFWorkbook wb2 = null;

 MacroEnabledExcelTemplateBus macroEnabledExcelTemplateBus;
 try {
     
  session = request.getSession(true);
     macroEnabledExcelTemplateBus = new MacroEnabledExcelTemplateBus();
     errors = new ArrayList<String>();
     msg = new ArrayList<String>();
     /*
      * Server folder path
      */
     tempPath = "C:\Documents and Settings\Raj\Desktop\Excel work";  
     // Use the server path where excel sheet templated to be uploaded
     logger.debug("Temp Folder path i.e. Server Folder :" + tempPath);
     if (userId != null) {
      logger.debug("user id not null");
      try {
       if (hasAccess) {
        // temp folder path for creating a temp template
        // We are creating a tempoarary template (person sprecific) so that more than one user can use the functuionality and 
        // original template remain uncorrupted
         tempFolderPath = tempPath + "\" + userId;
         existFile = new File(tempFolderPath);
         logger.debug("existFile");
         /*
         * checking whether the folder already exists on the
         * given path
         */
         if (existFile.exists()) {
         // deleting the existing directory
         existFolderAtNAS = MacroEnabledExcelTemplateBus.deleteDir(existFile);
         logger.debug("existFolderAtServer "+ existFolderAtServer);
         }
         if (existFolderAtServer) {
          file = new File(tempFolderPath);
          // Creates the directory
          boolean b = file.mkdir();
          if (b) {
             // template with macros at  sever
             inputFile = new FileInputStream(tempPath+ "\Template.xls");
             /*
              * copy the excel template with macro. True
              * is for copying all the attributes of
              * workbook
              */
             wb = new HSSFWorkbook(new POIFSFileSystem(inputFile), true);
               
             /*
              * writing the copied workbook to a new temp
              * template for processing
              */
             outputFile = new FileOutputStream(tempFolderPath+ "\tempTemplate.xls");
             wb.write(outputFile);
             /*
              * Processing the temp template
              */
             inputFile2 = new FileInputStream(tempFolderPath+ "\tempTemplate.xls");
             wb2 = new HSSFWorkbook(new POIFSFileSystem(inputFile2), true);
             /*
              * Building a data sheet and hide it. Data
              * sheet number is 1.
              */
               macroEnabledExcelTemplateBus.buildDataSheet(wb2);
               wb2.setSheetHidden(1, true);
             /*
              * Writing the data in main sheet
              */
             Sheet outputSheet = wb2.getSheetAt(0);
             // Setting the name of main sheet
             wb2.setSheetName(0, "MAIN DATA Sheet");
             // Creating the style for main sheet
             cs = wb2.createCellStyle();
             cs.setBorderBottom(CellStyle.BORDER_THIN);
             cs.setBorderLeft(CellStyle.BORDER_THIN);
             cs.setBorderRight(CellStyle.BORDER_THIN);
             // creating the font for main sheet
             font = wb2.createFont();
             font.setFontName("Arial");   // name of font
             font.setFontHeight((short) 200);
             // for setting the font we need to multiply the font size by 20.
             // For eg. setting font size 10, you need to multiply it by 20 i.e. 200.
             cs.setFont(font);
             /*
             * Getting the data for main sheet from DB
             */
             mainSheetData = macroEnabledExcelTemplateBus.getDataForMainSheet(parameter1, parameter2);
             totalNumberOfRows =  mainSheetData.length;
           
             /*
             *  adding Action Type validations
             */
             addressList = new CellRangeAddressList(1,totalNumberOfRows, 0, 0);
             dvHelper = outputSheet.getDataValidationHelper();
             dvConstraint = dvHelper.createFormulaListConstraint("Action"); // name od the list to be populated in excel sheet
             validation = dvHelper.createValidation(dvConstraint, addressList);
             outputSheet.addValidationData(validation);
             addressList = null;
             if (mainSheetData != null && mainSheetData.length > 0) {
              for (int rowCount = 0; rowCount < mainSheetData.length; ++rowCount) {
               // creating a new row for every record
               mainSheetRow = outputSheet.createRow(newRowMainSheet);
               
               // creating a new cell 
               mainSheetCell = mainSheetRow.createCell(newCellMainSheet);
               // writing the value in the cell
               mainSheetCell.setCellValue("");  // fetched it from db   mainSheetData[rowCount][6]
               // apply the css
                 mainSheetCell.setCellStyle(cs);
                 // setting the column width 
                 //we can give the integer value in palce of auto.
                 outputSheet.setColumnWidth(newCellMainSheet, auto);
                 // INCREASE THE VALUE TO CREATE A NEW CELL
                 ++newCellMainSheet;
 
                 // entity id data
                 mainSheetCell = mainSheetRow.createCell(newCellMainSheet);
                 // setting the cell datatype by default it is string
                 mainSheetCell.setCellType(Cell.CELL_TYPE_NUMERIC);
                 //writing the integer or double value
                 mainSheetCell.setCellValue(Double.parseDouble(mainSheetData[rowCount][6]));   
                 outputSheet.setColumnWidth(newCellMainSheet, 2560);
                 mainSheetCell.setCellStyle(cs);
                 ++newCellMainSheet;
                 /*
                 * adding  validations dat geeting populated on the basis of previous selected cellvalue
                 */
                 // 5 is column number from which the below validation applies 
                 // 6 is column number upto which the below validation applies
                 addressList = new CellRangeAddressList(rowCount + 1, rowCount + 1,5, 6);
                 dvHelper = outputSheet.getDataValidationHelper();
                 dvConstraint = dvHelper
                              .createFormulaListConstraint("INDIRECT(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE($E$"
                              + (rowCount + 2)+ ","&",""),"-",""),"/",""),",",""),"~","")," ",""))");
                 validation = dvHelper.createValidation(dvConstraint,addressList);
                 outputSheet.addValidationData(validation);
                 addressList = null;
                 // reset the cell value to 0 for creatibng the cell for new row 
                 newCellMainSheet = 0;
                 // creating the new row.
                 ++newRowMainSheet;
              }
             }
             // setting the content to response
             response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml");
             // setting the header name of excel sheet
             response.setHeader("Content-Disposition","attachment; filename=MACROEXCEL.xls");
             wb2.write(response.getOutputStream());
             // deleting the temp template and directory
             deletedDir = macroEnabledExcelTemplateBus.deleteDir(existFile);

            } else {
              logger.debug("Couldn't make a new folder.");
              // Couldn't make a new folder
            }
            } else {
            logger.debug("Folder already exists. getting error while deleting");
            // Folder already exists. getting error while deleting it.
          }
      }
     } 
    }
  } catch (FileNotFoundException fnfe) {
      logger.debug("error " + fnfe);
      
  } catch (IOException ioe) {
      logger.debug("error " + ioe);
      
  } catch (Exception e) {
      logger.debug("error " + e);
     
  } finally {
      // Flushing all the file streams
      inputFile.close();
      outputFile.close();
      inputFile2.close();
      wb2 = null;
      wb = null;
      file = null;
        existFile = null;
  }
     }else {
  logger.debug("user id is null");
  
     }

 } catch (NullPointerException npe) {
      logger.debug("error " + npe);
 } catch (Exception e1) {
      logger.debug("error " + e1);
 }
 
 return null;
    }
}
==============================================================================
/*
* class MacroEnabledExcelTemplateBus
*/

package com.tcs.reuse.business;

import java.io.File;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;



// TODO: Auto-generated Javadoc
/**
 * The Class MacroEnabledExcelTemplateBus.
 * 
 */
@SuppressWarnings("deprecation")
public class MacroEnabledExcelTemplateBus {
    /** The logger. */
    private static Logger logger = Logger.getLogger(package com.tcs.reuse.business.MacroEnabledExcelTemplateBus.class);
    

    /**
     * Builds the data sheet as tthe dummay databse to fetch the values for list in excel.
     * 
     * @param dataSheet
     *            the data sheet
     * @throws SQLException
     *             the sQL exception
     */
    public void buildDataSheet(HSSFWorkbook workbook) throws SQLException{
  Row row = null;
  Cell cell = null;
  Name name = null;
  String[][] countriesList = null;
  String[][] coverageTypeList = null;
  String poleTypeList[][] = null;
  String[][] iFGList = null;
  String[][] businessList = null;
  String[][] subBusinessList = null;
  String cellValue = "";
  String columnName = "A";
  int newCell = 0;
  int newRow = 0;
  Sheet dataSheet = workbook.createSheet("DataSheet");
  HSSFCellStyle style = workbook.createCellStyle();
  style.setBorderBottom((short) 10); // single line border
  style.setFillForegroundColor(HSSFColor.RED.index);
  /**
   * action data mapping starts new row value = 1 new cell number = 0;
   */
  // CREATING CELL FOR HEADER IN DATASHEET
  row = dataSheet.createRow(newRow);
  ++newRow;
  cell = row.createCell(newCell);
  cell.setCellValue("Action");
  cell.setCellStyle(style);
  // WRITING ALL THE Actions
  row = dataSheet.createRow(newRow);
  ++newRow;
  ++newRow;
  cell = row.createCell(newCell);
  cell.setCellValue(new HSSFRichTextString("Add"));
  ++newCell;
  cell = row.createCell(newCell);
  cell.setCellValue(new HSSFRichTextString("Update"));
  ++newCell;
  cell = row.createCell(newCell);
  cell.setCellValue(new HSSFRichTextString("Delete"));

  // CREATING THE FORMULA RANGE FOR Action
  columnName = getCellColumnCount(3);
  String actionFormulaRange = "Datasheet!$A$" + (newRow - 1) + ":$"+ columnName + "$" + (newRow - 1);

  // SETTING THE NAME OF THE Action LIST
  name = dataSheet.getWorkbook().createName();
  // Name of List
  name.setNameName("Action");
  name.setRefersToFormula(actionFormulaRange);
  newCell = 0;
  // password protecting the datasheet
  dataSheet.protectSheet("password");
    } // end of build datasheet method
    /**
     * Gets the data for main sheet.
     * 
     * @param listSize
     *            the list size
     * @return the data for main sheet
     * 
     * @storeProcedureParams
     */

    public String[][] getDataForMainSheet(String parameter1, String parameter2
     ) throws SQLException {
 String[][] dataForMainSheet = null;
 ArrayList tempData = null;
 DBUtilParam params = new DBUtilParam(3);
 try {
     // fetch the resuklt set from DB
 } catch (WFException wfe) {
     throw wfe;
 } catch (Exception e) { //
 } finally {
     params = null;
 }
 return dataForMainSheet;
    }

    /**
     * Cell column count for determining the last column number in excel.
     * 
     * @param listSize
     *            the list size
     * @return the string
     * @limitations maximum listSize 702
     */
    public String getCellColumnCount(int listSize) {
 String columnName = "A";
 String alphabetArray[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I",
  "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
  "V", "W", "X", "Y", "Z" };
 int firstCharIndex = listSize / 26;
 int secondCharIndex = listSize % 26;
 if (firstCharIndex == 0 && secondCharIndex != 0) {
     columnName = alphabetArray[secondCharIndex - 1];
 } else if (firstCharIndex != 0 && secondCharIndex == 0) {
     columnName = alphabetArray[firstCharIndex - 1];
 } else {
     columnName = alphabetArray[firstCharIndex - 1]
      + alphabetArray[secondCharIndex - 1];
 }
 return columnName;
    }

    /**
     * Replace special char from list name with blank.
     * 
     * @param listName
     *            the list name
     * @return the string
     */
    public String replaceSpecialCharFromName(String listName) {
 String arrSpecialChar[] = { "&", "-", "/", ",", "~", " " };
 String newString = listName;
 for (int i = 0; i < arrSpecialChar.length; i++)
     newString = StringUtils.replace(newString, arrSpecialChar[i], "");
 return newString;

    }

   

    /**
     * Deletes all files and subdirectories under dir. Returns true if all
     * deletions were successful. If a deletion fails, the method stops
     * attempting to delete and returns false.
     * 
     * @param dir
     * @return boolean
     */
    public static boolean deleteDir(File dir) {
 if (dir.isDirectory()) {
     String[] children = dir.list();
     for (int i = 0; i < children.length; i++) {
  boolean success = deleteDir(new File(dir, children[i]));
  if (!success) {
      return false;
  }
     }
 }

 // The directory is now empty so delete it
 return dir.delete();
    }
}

[ Read More ]
Read more...
Saturday, October 13, 2012

Exporting the data from the Database using java

Posted by Raju Gupta at 3:00 AM – 0 comments
 
This Program is used to retrive the data from the Database .

import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelFile {
 public static void main(String[] args) {   
  // TODO Auto-generated method stub   
  Connection con=null;   
  try {     
   String action,connString=null;   
   String start,end;   
   String smartcardquery=null;   
   ResultSet rssmartdata=null;   
   PreparedStatement pssmartdata=null;   
   Scanner sc=new Scanner(System.in);   
   System.out.print("Enter username"); // Enter the user name to connect the DB  
   String user=sc.next();   
   System.out.print("Enter password");  // Enter the password to connect the DB 
   String pwd= sc.next();   
   Class.forName("oracle.jdbc.OracleDriver");   
   System.out.println("Oracle JDBC driver loaded ok.");   
   connString = "jdbc:oracle:thin:" + user + "/" + pwd   
     + "@localhost:port no";   
   con = DriverManager.getConnection(connString);   
   System.out.println("Enter number of sheets to be created");   
   int numOfSheets=sc.nextInt();   
   String[] sheets = new String[numOfSheets];   
   HSSFWorkbook wb = new HSSFWorkbook();    
   for (int i=0; i<=sheets.length-1; i++)   
   {   
    System.out.println("1.ADD ITEM\n2.DELETE ITEM\n");   
    System.out.print("Enter the action to which report is needed ");   
    action=sc.next();   
    HSSFSheet sheet = wb.createSheet(action);              
    HSSFRow rowhead = sheet.createRow((short) 0);              
    rowhead.createCell((short) 0).setCellValue("ITEM NAME");                           
    rowhead.createCell((short) 1).setCellValue("QUANTITY)");                           
    rowhead.createCell((short) 2).setCellValue(" COST");                           
    smartcardquery = "select ITEMNAME,QUANTITY,COST from INVENTORY where action=?;    
      pssmartdata = con.prepareStatement(smartcardquery);   
    pssmartdata.setString(1, action);   
    rssmartdata=pssmartdata.executeQuery();    
    while (rssmartdata.next()) {                                   
     HSSFRow row = sheet.createRow((short) index);                                   
     row.createCell((short) 0).setCellValue(rssmartdata.getString(1));                                   
     row.createCell((short) 1).setCellValue(rssmartdata.getString(2));                                   
     row.createCell((short) 2).setCellValue(rssmartdata.getString(3));    
    }    
   }   
   FileOutputStream fileOut = new FileOutputStream("Report.xls");                           
   wb.write(fileOut);   
   fileOut.close();                           
   System.out.println("Data is saved in excel file.");                           
   rssmartdata.close();                           
   con.close();                   
  }    
  catch (Exception e) {   
   e.printStackTrace();   

  }   

 }
}


[ Read More ]
Read more...
Wednesday, October 10, 2012

Data Migration from Excelsheet to database using Java

Posted by Raju Gupta at 11:15 AM – 0 comments
 

This java code reads the excel sheet columnwise and then insert the data in database through SQL insert statement. The name of excelsheet columsn matches with the databse table columns.


import java.io.*;
import java.util.*;
import java.sql.*;
import jxl.*;
import oracle.jdbc.OracleResultSet;


public class interfaceDataImport  
{
    private Connection  conn                    = null;    // Connection Object
    private String         dbUser                  = "raj";  // DataBase UserName
    private String         dbPassword              = "raj";  // DataBase Password
 private String     connectionURL = "jdbc:oracle:thin:@locahost:1521:raj";    // Connection URL
 
 
 
 
 // Function to open DB Connection that returns Connection Object
    public Connection connect() throws SQLException, IllegalAccessException, InstantiationException, ClassNotFoundException {
        String driver_class  = "oracle.jdbc.driver.OracleDriver";
        String connectionURL = "jdbc:oracle:thin:@localhost:1521:raj";
        try {
            Class.forName(driver_class).newInstance();
            
            conn = DriverManager.getConnection(connectionURL, dbUser, dbPassword);
           // conn.setAutoCommit(true);
            System.out.println("Connected.n");
        }
        catch (IllegalAccessException e) {
            System.out.println("Illegal Access Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        }
        catch (InstantiationException e) {
            System.out.println("Instantiation Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        }
        catch (ClassNotFoundException e) {
            System.out.println("Class Not Found Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        }
        catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Open Connection).");
            e.printStackTrace();
            throw e;
        }
        return conn;
    }


    // Function to close the DB Connection
    public void disconnect() throws SQLException {
        try {
            conn.close();
            System.out.println("Disconnected.n");
        }
        catch (SQLException e) {
            System.out.println("Caught SQL Exception: (Closing Connection).");
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback();
                }
                catch (SQLException e2) {
                    System.out.println("Caught SQL (Rollback Failed) Exception.");
                    e2.printStackTrace();
                }
            }
            throw e;
        }
    }


    private void getFileData(File file) throws Exception{
        System.out.println("inside getFileData.......");
        
        ArrayList alColumnNames = new ArrayList();
        File inputWorkbook = file;
  int inputSheetCount = 0;
  int inputSheetRowCount = 0;
  int inputSheetColCount = 0;
  String sheetName = "";
  String sheetColumn = "";
  String sheetValue = "";
//  String sSqlSelect = "";

        try{
            Workbook w1nput = Workbook.getWorkbook(inputWorkbook);

   inputSheetCount = w1nput.getNumberOfSheets();  
   
            for(int sheetCount=0; sheetCount<inputSheetCount; sheetCount++){
                
                Sheet s = w1nput.getSheet(sheetCount);
                inputSheetRowCount = s.getRows();
                inputSheetColCount = s.getColumns();
    sheetName = s.getName();
                System.out.println("Copying...");

//    sSqlSelect = "Select count(*) count from "+sheetName;

//    if(selectRecord(sheetName) <= 0 ){

     System.out.println("TABLE..."+sheetName+"...EMPTY...");

     StringBuffer sbInsertColumn = new StringBuffer();
     String sInsCol = "";
     String sInsVal = "";
     String sSqlInsert = "";

     sbInsertColumn.append("INSERT INTO "+sheetName+" ( ");
     
     for(int i=0;i<inputSheetColCount;i++){
      Cell cData = s.getCell(i,0);        // gets Column Name
      sheetColumn = cData.getContents();
      sheetColumn=(sheetColumn!=null)?sheetColumn.trim():"";

      sbInsertColumn.append(sheetColumn+" , " );
     }

     sInsCol=sbInsertColumn.toString().trim();
 //    if(sInsCol.endsWith(", ")) {
      sInsCol=sInsCol.substring(0,(sInsCol.length()-2));
 //    }

     sInsCol = sInsCol+" ) ";


     for(int j=2;j<inputSheetRowCount;j++){
      StringBuffer sbInsertValue = new StringBuffer();
      sbInsertValue.append(" VALUES ( ");

      for(int k=0;k<inputSheetColCount;k++){
       Cell cValue = s.getCell(k,j);        // gets Column Value
       sheetValue = cValue.getContents();
       sheetValue=(sheetValue!=null)?sheetValue.trim():"";

 /*
       if(sheetValue.equalsIgnoreCase("(null)") || sheetValue.equalsIgnoreCase("null") ){
        sheetValue = "";
       }
 */
       sbInsertValue.append(" '"+sheetValue+"' , " );
      }

      sInsVal=sbInsertValue.toString().trim();
 //     if(sInsVal.endsWith(", ")) {
       sInsVal=sInsVal.substring(0,(sInsVal.length()-2));
 //     }

      sInsVal = sInsVal+" )";

      sSqlInsert = sInsCol + sInsVal;

      System.out.println("INSERT SQL::::::::j="+j+"::::::"+sSqlInsert);

      int count=insertRecord(sSqlInsert);

     }// for(int j=2;j<inputSheetRowCount;j++){

//    }// if(selectRecord(sSqlSelect) > 0 )

            }// end for

        }
        catch(Exception e){
            System.out.println("Exception getFileData::"+ e);
            e.printStackTrace();
            throw e;
        }

    }// end getFileData(File file)
    

 public int insertRecord(String sqlInsert) throws Exception
 {
         int count = 0;
   Statement stmt = null;
  try
  {
   stmt = conn.createStatement();
   System.out.println("Insert statement made...");
   count = stmt.executeUpdate(sqlInsert);
   System.out.println("query  executed...");
   conn.commit();
   stmt.close();
   stmt = null;

  }
  catch(Exception e)
  {
   System.out.println("Caught Exception... "+e);
  }
  finally{
   if(stmt!=null){
    stmt.close();
   }
  }
  return count;
 }



 public int selectRecord(String tableName) throws Exception
 {
         ResultSet rs = null;
   Statement stmt = null;
   Statement stmt1 = null;
   String sDeleteSql = "";
   String sSelectSql = "";
         int count = 0;
  try
  {
   sDeleteSql = "Delete from "+tableName;
   System.out.println("DELETE SQL::::::::"+sDeleteSql);

   stmt1 = conn.createStatement();
   stmt1.executeUpdate(sDeleteSql);
   System.out.println("Delete query  executed...");
   stmt1.close();
   stmt1 = null;

   sSelectSql = "Select count(*) count from "+tableName;
   System.out.println("SELECT SQL::::::::"+sSelectSql);

   stmt = conn.createStatement();
   System.out.println("Select statement made...");
   rs = stmt.executeQuery(sSelectSql);
   System.out.println("Select query  executed...");
   if(rs != null && rs.next())
   {
    count =rs.getInt("count");
   }
   System.out.println("Count  "+count);
   stmt.close();
   rs.close();
   stmt = null;
  }
  catch(Exception e)
  {
   System.out.println("Caught Exception  "+e);
  }
  finally{
   if(stmt!=null){
    stmt.close();
   }
   if(stmt1!=null){
    stmt1.close();
   }
   if(rs!=null){
    rs.close();
   }
  }
  return count;
 }



 public static void main(String[] args) 
 {
  System.out.println("Hello World!");

  try{

  // write the file object to be uploaded to blob
        BufferedInputStream  bis = new BufferedInputStream(new FileInputStream("c:\Import-Data.xls"));

  File fileOut = new File("FileOut");
  FileOutputStream fos = new FileOutputStream(fileOut);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

  byte[] buff = new byte[100000];
  int bytesRead; 

  // Simple read/write loop.
  while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  bos.write(buff, 0, bytesRead);
  }
  // file write code over
  System.out.println("File writen successfully");



  interfaceDataImport pdi = new interfaceDataImport();
  pdi.connect();

  pdi.getFileData(fileOut);

  pdi.disconnect();

  fos.close();


  }
  catch(Exception e){
   e.printStackTrace();
  }



 }
}


[ Read More ]
Read more...
Monday, September 17, 2012

Excel functionalities using java

Posted by Admin at 12:11 PM – 0 comments
 

This is used to generate password protected excel sheet with some cells editable and non editable cells. Some functions are used to create dropdown in a cell with constaraints and to create hyperlink in a cell pointing to the desired URL,to apply font to the cells according to the users' requirement,create freeze pane in a sheet, make a sheet in a workbook as hidden,to create comment for a cell and Also,to create merged cell .



import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Comment;

/**
 * This class is used to generate password protected  excel sheet with some cells editable and non editable cells.
 * Some functions are used to create dropdown in a cell  with constaraints and to create hyperlink in a cell pointing to the desired URL,to apply  font to the cells according to the users' requirement,create freeze pane in a sheet,
 * make a sheet in a workbook as hidden,to create comment for a cell and Also,to create merged cell . 
 *
 */


@SuppressWarnings("deprecation")
public class ProtectedSheet {
 public static void main(String arg[]) {
  try{
   //reading the file provide the appropriate path
   FileOutputStream out=new FileOutputStream("protected.xls");
   //Creating Workbook
   Workbook wb = new HSSFWorkbook();
   Sheet sheet = wb.createSheet("employeedetails");//sheet is created 
   Sheet sheet1=wb.createSheet("HiddenSheet");
   //setSheetHidden function is used to make the  sheet as hidden
   wb.setSheetHidden(1,true);
   //creating CellStyle  to apply it into cell
   CellStyle style = wb.createCellStyle();
   CellStyle style1 = wb.createCellStyle();
   //Font is used for setting the font to a cell
   Font font = wb.createFont();
   font.setBoldweight(Font.BOLDWEIGHT_BOLD);
   style.setFont(font);
   style.setLocked(true);
   style1.setFont(font);
   style1.setLocked(false);//setLocked function is used to make a cell lock or unlock ,if it false means the cell value is editable
   style1.setWrapText(true);// setWrapText function is used to display the cell value in one line
   CreationHelper createHelper = wb.getCreationHelper();
   //cell style for hyperlinks

   CellStyle hlink_style = wb.createCellStyle();
   Font hlink_font = wb.createFont();
   hlink_font.setUnderline(Font.U_SINGLE);
   hlink_font.setColor(IndexedColors.BLUE.getIndex());
   hlink_style.setFont(hlink_font);
   //filling the excel sheet
   for(int i=0;i<10;i++)
   {
    Row row = sheet.createRow(i);
    Cell cell =row.createCell((short)0);
    cell.setCellValue("EmployeeName");
    cell.setCellStyle(style);
    cell=row.createCell((short)1);
    cell.setCellValue("Employee ID");
    cell.setCellStyle(style);
    cell=row.createCell((short)2);
    cell.setCellValue("Project");
    cell.setCellStyle(style1);//Applying style to a cell
    cell=row.createCell((short)3);
    cell.setCellValue("ProjectDuration");//Applying style to a cell
    cell.setCellStyle(style1);
    //Creating dropdown in a sheet in the  required  position
    CellRangeAddressList addressList = new  CellRangeAddressList(i, i, 3, 3);
    //dropdown is taking explicit values mentioned in the String Array
    DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(new String[]{"1", "2", "3"});

    HSSFDataValidation dataValidation = new HSSFDataValidation(addressList, dvConstraint);
    dataValidation.setSuppressDropDownArrow(false);
    ((HSSFSheet) sheet).addValidationData(dataValidation);
    cell=row.createCell((short)4);
    cell.setCellStyle(style1);
    CellRangeAddressList addressList1 = new  CellRangeAddressList(i, i, 4, 4);
    //adding constraint to the dropdown depending the value of the previous dropdown the value will be displayed in the curent dropdown
    DVConstraint dvConstraint1=DVConstraint.createFormulaListConstraint("IF(INDIRECT(\"D\"&ROW())=1,'employeedetails'!$A$1:$B$1,IF(INDIRECT(\"D\"&ROW())=2,"+
    "'employeedetails'!$A$1:$B$1,IF(INDIRECT(\"D\"&ROW())=3,'employeedetails'!$A$1:$B$1,)))");

    HSSFDataValidation dataValidation1 = new HSSFDataValidation(addressList1, dvConstraint1);
    dataValidation1.setSuppressDropDownArrow(false);
    ((HSSFSheet) sheet).addValidationData(dataValidation1);
    cell=row.createCell((short)5);
    cell.setCellValue("GOOGLE");
    Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
    link.setAddress("https://www.google.com");
    cell.setHyperlink(link);
    cell.setCellStyle(hlink_style);
    cell=row.createCell((short)6);
    cell.setCellValue("Merged cell");
    //Merging the cells
    sheet.addMergedRegion(new CellRangeAddress(i,i,6,7));
    Drawing drawing = sheet.createDrawingPatriarch();
    ClientAnchor anchor = createHelper.createClientAnchor();
    anchor.setCol1(cell.getColumnIndex());
    anchor.setCol2(cell.getColumnIndex()+5);
    anchor.setRow1(row.getRowNum());
    anchor.setRow2(row.getRowNum()+5);
    //Adding comment to a cell
    Comment comment =drawing.createCellComment(anchor);
    RichTextString str = createHelper.createRichTextString("Hello, World!");//createRichTextString function is used to add comment for a cell
    comment.setString(str);
    cell.setCellComment(comment);
   }
   //Creating freezepane for a sheet
   sheet.createFreezePane(0, 5, 0,5 );
   //Protecting a sheet with Password
   ((HSSFSheet)sheet).protectSheet("DocuShare");
   System.out.println("Protected Sheet is created");
   wb.write(out);
   out.close();
  } catch(Exception e){
   e.printStackTrace();
  }
 }

}


[ Read More ]
Read more...
Sunday, September 16, 2012

Advanced excel data extraction using SS User Model

Posted by Admin at 12:39 AM – 0 comments
 

/**
 * 
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class SpreadSheetReader {
 Object row = null;
 Cell cell = null;

 public static int Cell_Total = 0;
 public static int Cell_Actual = 0;

 public static void main(String args[]) {
  SpreadSheetReader read_Obj = new SpreadSheetReader();
  try {
   read_Obj.readFile();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }

 }

 /*
  * To read the file
  */

 private void readFile() throws FileNotFoundException {
  File inputFile = new File("D:\\EPIW.xls");
  FileInputStream fileIStream = new FileInputStream(inputFile);
  try {
   Workbook workbook = WorkbookFactory.create(fileIStream);
   for (int Sh_Count = 0; Sh_Count < workbook.getNumberOfSheets(); Sh_Count++) {
    Sheet sheet = workbook.getSheetAt(Sh_Count);
    System.out.println("Sheet Name :"
      + workbook.getSheetName(Sh_Count));
    
    read_Rows(sheet);
   
    read_Columns(sheet);

   }

  } catch (IOException e) {

   e.printStackTrace();
  } catch (InvalidFormatException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 /*
  * Reading column wise
  */
 @SuppressWarnings("deprecation")
 private void read_Columns(Sheet sheet) {
  Iterator rows = sheet.rowIterator();
  int i = 0;
  while (i <= Cell_Total) {
   try {
    while (rows.hasNext()) {
     try {
      row = rows.next();
      Cell_Actual =  ((org.apache.poi.ss.usermodel.Row) row).getLastCellNum();

      if (Cell_Total < Cell_Actual) {
       Cell_Total = Cell_Actual;
      
      }

      cell = ((org.apache.poi.ss.usermodel.Row) row).getCell(i);
      getcellValue(cell);
     } catch (RuntimeException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    i++;
    rows = sheet.rowIterator();
   } catch (RuntimeException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  Cell_Total = 0;
 }

 /*
  * Reading Row wise
  */

 private void read_Rows(Sheet sheet) {
  System.out.println("Reading Rows....");
  Iterator rows = sheet.rowIterator();
  while (rows.hasNext()) {
   try {
    row =rows.next();
    Iterator cells = ((org.apache.poi.ss.usermodel.Row) row).cellIterator();
    while (cells.hasNext()) {
     cell = (Cell) cells.next();
     getcellValue(cell);
    }
   } catch (RuntimeException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }

 /*
  * Handling various types of cells
  * 
  */
 private void getcellValue(Cell cell2) {
  try {

   if ((cell2.getCellType() == Cell.CELL_TYPE_STRING)) {
    System.out.println(cell2.getStringCellValue());
   }  else if (cell2.getCellType() == Cell.CELL_TYPE_NUMERIC) {
   } else if (cell2.getCellType() == Cell.CELL_TYPE_FORMULA) {

   } else if (cell2.getCellType() == Cell.CELL_TYPE_BLANK) {

   } else {
   }

  } catch (Exception e) {
   e.getMessage();
  }

 }
}

[ Read More ]
Read more...

Creation Of Excel Sheet using Java

Posted by Admin at 12:37 AM – 0 comments
 

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import org.apache.poi.hssf.util.HSSFColor.LAVENDER;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XSSFExcelGenerator {
            protected void buildExcelDocument(String fileName) {
                        FileOutputStream fileOutputStream = null;
                        try {
                                    fileOutputStream = new FileOutputStream(fileName);
                                    // Create Sheet.
                                    XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
                                    XSSFSheet sheet = xssfWorkbook.createSheet("SampleExcelSheet");
                                    // Font setting for sheet.
                                    XSSFFont font = xssfWorkbook.createFont();
                                    font.setBoldweight((short) 700);
                                    sheet.setDefaultColumnWidth(30);
                                    // Create Styles for sheet.
                                    XSSFCellStyle headerStyle = xssfWorkbook.createCellStyle();
                                    headerStyle.setFillForegroundColor(LAVENDER.index);
                                    headerStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
                                    headerStyle.setFont(font);
                                    XSSFCellStyle dataStyle = xssfWorkbook.createCellStyle();
                                    dataStyle.setWrapText(true);
                                    // Create Header Row
                                    XSSFRow headerRow = sheet.createRow(0);
                                    // Write row for header
                                    XSSFCell headerCell1 = headerRow.createCell(0);
                                    headerCell1.setCellStyle(headerStyle);
                                    headerCell1.setCellValue("Employee Name");
                                    XSSFCell headerCell2 = headerRow.createCell(1);
                                    headerCell2.setCellStyle(headerStyle);
                                    headerCell2.setCellValue("Designation");
                                    XSSFCell headerCell3 = headerRow.createCell(2);
                                    headerCell3.setCellStyle(headerStyle);
                                    headerCell3.setCellValue("Country");
                                    // Create First Data Row
                                    XSSFRow dataRow = sheet.createRow(1);
                                    // Write data in data row
                                    XSSFCell cell1 = dataRow.createCell(0);
                                    cell1.setCellStyle(dataStyle);
                                    cell1.setCellValue(new XSSFRichTextString("Sandeep"));
                                    XSSFCell cell2 = dataRow.createCell(1);
                                    cell2.setCellStyle(dataStyle);
                                    cell2.setCellValue(new XSSFRichTextString("Software Engineer"));
                                    XSSFCell cell3 = dataRow.createCell(2);
                                    cell3.setCellStyle(dataStyle);
                                    cell3.setCellValue(new XSSFRichTextString("India"));
                                    // write in excel
                                    xssfWorkbook.write(fileOutputStream);
                        } catch (Exception e) {
                                    e.printStackTrace();
                        } finally {
                                    /*
                                     * Close File Output Stream
                                     */
                                    try {
                                                if (fileOutputStream != null) {
                                                            fileOutputStream.close();
                                                }
                                    } catch (IOException ex) {
                                                ex.printStackTrace();
                                    }
                        }
            }
            public static void main(String[] args) {
                        /*
                         * call method and pass as an argument path of excel file. Please make
                         * sure that path of excel file is correct otherwise it will throw
                         * FileNotFound Exception.
                         */
                        new XSSFExcelGenerator().buildExcelDocument("C:" + File.separator
                                                + "files" + File.separator + "SampleExcel.xlsx");
            }
}

[ Read More ]
Read more...
Saturday, September 15, 2012

A Formatting Guide in Excel using POI

Posted by Admin at 11:33 PM – 0 comments
 
This Code Snippet throws light on the following POI features:
1) Set Row Height
2) Freeze Pane
3) Set Column Width
4) Align the Contents of the Cell
5) Set Foreground Color

//Create new workbook
wb = new HSSFWorkbook();
//Create a new sheet
Sheet sheet = wb.createSheet("Formatting_Test");
//Create a new row
Row hRow = sheet.createRow(0);
//Set height if you need - optional
hRow.setHeightInPoints(7.25f);
//Use this statement to freeze pane the row created - optional
sheet.createFreezePane(0, 1);
//Create a new cell
Cell hCell = hRow.createCell(0);
//For setting the Column width - optional
//The width is in units of 1/256th of a character width
//So, 256*6 will be 6 character widths
sheet.setColumnWidth(0, 256*6);
//Center Alignment - optional
hCell.setAlignment(CellStyle.ALIGN_CENTER);
//Setting blue color as BG color - optional
hCell.setFillForegroundColor(IndexedColors.BLUE.getIndex());

[ Read More ]
Read more...

Output an Excel file from JAX RS

Posted by Admin at 5:53 AM – 0 comments
 

Output an Excel file from JAX-RS : Produces an excel(.xlsx) file and output is prompted to the user.


package com.homedepot.ta.wh.md.service;

import java.io.File;
import java.io.FileOutputStream;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


@Path("/excel")

//Output an Excel file from JAX-RS
public class excelgenerator  {
 @GET
 // mime type for excel output
 @Produces("application/vnd.ms-excel")
 @Path("/get")
 

    ResponseBuilder rb=null;
 
 /*
  * Method which generates an excel file
  * Writes to an output stream
  * Appends the file in a response
  * Builds the response so as to produce an .xlsx file
  * 
  */
 public Response getExcel() {
 
  File file = new File("Excel.xlsx"); 
          try{
            Workbook wb = new XSSFWorkbook();
      FileOutputStream fos = new FileOutputStream(file);
            wb.write(fos);
            fos.close();
            rb = Response.ok((Object) file);
         rb.header("Content-Disposition","attachment; filename=Excel.xlsx");
 } catch (Exception e) {
   System.out.println(e.getMessage());
 }
    return rb.build();      
 }
  }

[ Read More ]
Read more...

Insert Image in excel | Java Example

Posted by Admin at 1:38 AM – 0 comments
 
The program inserts an image to a specified cell of an excel sheet

 package pkg.util.excel;
 
 import java.io.ByteArrayOutputStream;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 
 import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
 import org.apache.poi.hssf.usermodel.HSSFPatriarch;
 import org.apache.poi.hssf.usermodel.HSSFSheet;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;

 /**
  *  Jars needed for the program to run: 
  *  poi-3.8-beta4-20110826.jar
  * poi-excelant-3.8-beta4-20110826.jar
  * poi-ooxml-3.8-beta4-20110826.jar
  * poi-ooxml-schemas-3.8-beta4-20110826.jar
  * poi-scratchpad-3.8-beta4-20110826.jar
  *  commons-codec-1.6.jar
  */
 public class ImageInsert
 {
  /**
   * The code inserts an image to a specific 
   * cell of a excel sheet
   */
  public static void main(String[] args)
  {
 
   try
   {
    //Creating a excel workbook
    HSSFWorkbook wb=new HSSFWorkbook();
    //Creating a excel sheet named "test" within the workbook 
    HSSFSheet testsheet=wb.createSheet("test");
    System.out.println("The work book is created");
    //Pointing the excel file to FileOutputStream where image needs to be inserted
    FileOutputStream fos=new FileOutputStream("C:\\ExcelUtil\\sample.xls");
    System.out.println("File sample.xls is created");
    //Pointing the image file to FileInputStream which needs to be inserted in excel sheet
    FileInputStream fis=new FileInputStream("C:\\ExcelUtil\\sign.jpg");
    //Creating a ByteArrayOutputStream object
    ByteArrayOutputStream img_bytes=new ByteArrayOutputStream();
    int b;
    //The loop reads each byte from input stream and puts it into the byte array    
    while((b=fis.read())!=-1)
    img_bytes.write(b);
    //Closing the input stream as it is not required further
    fis.close();
    //Creating HSSFClientAnchor object
    HSSFClientAnchor anchor = new HSSFClientAnchor();
    int col1=1,row1=1;
    //HSSFClientAnchor object mainly sets the excel cell location where 
    //the image needs to be inserted
    //(col1, row1, x1, y1, col2, row2, x2, y2)   
    anchor.setAnchor((short)col1, row1, 0, 0,(short) ++col1, ++row1, 0, 0);
    anchor.setAnchorType(2);
    //Converts the byte array stream to JPEG image 
    int index=wb.addPicture(img_bytes.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG);
    //Gets sheet from the workbook
    HSSFSheet sheet=wb.getSheet("test");
    //Creating HSSFPatriarch object
    HSSFPatriarch patriarch=sheet.createDrawingPatriarch();
    //Creating picture with anchor and index information
    patriarch.createPicture(anchor,index);
    //Write workbook with the data
    wb.write(fos);
    System.out.println("Writing data to the xls file");
    //Close FileOutputStream as it will no longer be required
    fos.close();
    System.out.println("File closed");
   }
   catch(IOException ioe)
   {
   System.out.println("Hi ! You got an exception. "+ioe.getMessage());
   }
  }
 }

[ Read More ]
Read more...

Extraction of content from Notepad to Excel in a alinged manner

Posted by Admin at 1:03 AM – 0 comments
 

This Java Program helps in extracting the content form Notepad to Excel in a clear and alinged format


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.File;
import java.util.*;


public class DemoJFileChooserF extends JPanel
   implements ActionListener {
   JButton go;
   JTextField go1;
   JComboBox go2;
   JFileChooser chooser;
   String choosertitle;

  public DemoJFileChooserF() {
    go = new JButton("Start");
    go1 = new JTextField(10);

  
   go2.addActionListener(this);
    go1.addActionListener(this);
    go.addActionListener(this);
    add(go);
    add(go1);
  
   }

  public void actionPerformed(ActionEvent e) {
    int result;

    chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle(choosertitle);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //
    // disable the "All files" option.
    //
    chooser.setAcceptAllFileFilterUsed(false);
    //
    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
      //System.out.println("getCurrentDirectory(): "+  chooser.getCurrentDirectory());
       File curFolder = chooser.getSelectedFile();
         File[] listofFiles = curFolder.listFiles();
         if (listofFiles == null) {
        // Either dir does not exist or is not a directory
         }
         else {
             System.out.println("List Of Files......................");
             for (int i=0; i<listofFiles.length; i++) {
            // Get filename of file or directory
                    System.out.println(listofFiles[i].toString());
                    FileReadF.report(listofFiles[i].toString());
        }
 }
      
       
        System.out.println("getSelectedFile() : " +  chooser.getSelectedFile());
        System.out.println(go1.getText());
        System.out.println(go2.getSelectedItem());
      }
      else {
        System.out.println("No Selection ");
      }
     }

     public Dimension getPreferredSize(){
        return new Dimension(200, 200);
     }

    public static void main(String s[]) {
        JFrame frame = new JFrame("");
        DemoJFileChooserF panel = new DemoJFileChooserF();
        frame.addWindowListener(
        new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
        System.exit(0);
          }
      }
      );
    frame.getContentPane().add(panel,"Center");
    frame.setSize(panel.getPreferredSize());
    frame.setVisible(true);
    }
}

[ Read More ]
Read more...
Thursday, September 13, 2012

A program which merges two excel sheets using Java

Posted by Admin at 10:23 PM – 0 comments
 

This program will merge two excel sheets with homogenous data


import java.io.FileInputStream;   
import java.io.FileOutputStream;   
import java.io.IOException;   
import java.io.InputStream;   
import java.util.ArrayList;   
import java.util.Iterator;   
import java.util.Properties;   
  
import org.apache.poi.hssf.usermodel.HSSFCell;   
import org.apache.poi.hssf.usermodel.HSSFRow;   
import org.apache.poi.hssf.usermodel.HSSFSheet;   
import org.apache.poi.hssf.usermodel.HSSFWorkbook;   
import org.apache.poi.ss.usermodel.Cell;   
import org.apache.poi.ss.usermodel.Row;   
import org.apache.poi.ss.usermodel.Sheet;   
import org.apache.poi.ss.usermodel.Workbook;   
import org.apache.poi.xssf.usermodel.XSSFWorkbook;   
  
public class MergeExcel   
{   
  public static void main(String args[]) throws Exception   
  {   
      MergeExcel mergeExcel = new MergeExcel();   
      Workbook workBook1 = mergeExcel.checkFileFormat("first excel");   
     Workbook workBook2 = mergeExcel.checkFileFormat("second excel");   
     String path="result excel";   
      ArrayList<ArrayListRows> rowsArrayList = mergeExcel.getObjectsFromWorkBook(workBook1);     
      ArrayList<ArrayListRows> rowsArrayList1 = mergeExcel.getObjectsFromWorkBook(workBook2);   
       
      ArrayListRows firstRowList1 = rowsArrayList.get(0);   
      rowsArrayList.remove(0);   
      ArrayListRows firstRowList2 = rowsArrayList1.get(0);   
      rowsArrayList1.remove(0);   
      ArrayList<Integer> tot = mergeExcel.compareHeadings(firstRowList1,firstRowList2);   
      rowsArrayList1 = mergeExcel.sortColoumns(rowsArrayList1,tot);   
      ArrayList<ArrayListRows> totalList = mergeExcel.addRows(rowsArrayList,rowsArrayList1);   
      mergeExcel.writeToFile(path,totalList,firstRowList1);   
     /* Iterator<ArrayListRows> hfgks = totalList.iterator();  
      while(hfgks.hasNext())  
          System.out.println(((ArrayListRows)hfgks.next()).coloumns);*/  
         
  }   
  public void writeToFile(String path,ArrayList<ArrayListRows> totalList,ArrayListRows firstRowList1) throws Exception   
    {   
        HSSFWorkbook wb1 = new HSSFWorkbook();   
  
        HSSFSheet sheet1 = wb1.createSheet("new sheet");   
        for(int k=0;k<HSSFSheet.INITIAL_CAPACITY;k++)   
        {   
            sheet1.setColumnWidth( k, (short) 5000);   
        }   
              
            HSSFRow newTitleRow = sheet1.createRow((short)0);   
                     
             for(int index=0;index<firstRowList1.coloumns.size();index++)   
                  {   
                   newTitleRow.createCell(index).setCellValue(firstRowList1.coloumns.get(index));   
                  }                
               for(int index=0;index<totalList.size();index++)   
               {   
                      
                   HSSFRow newRow = sheet1.createRow((short)(index+1));   
                   ArrayListRows temp = totalList.get(index);   
                   for(int index1=0;index1<temp.coloumns.size();index1++)   
                      {   
  
                     HSSFCell cel =  newRow.createCell(index1);   
                          cel.setCellValue((temp.coloumns.get(index1)));   
  
                      }   
                     
               }   
                FileOutputStream fileOut = new FileOutputStream(path);   
                wb1.write(fileOut);   
                fileOut.close();      
                System.out.println("result.xls created Sucessfully");   
                  
                
                  
        }   
  
       
  public ArrayList<ArrayListRows> sortColoumns(ArrayList<ArrayListRows> rowsList,ArrayList<Integer> tot)   
  {   
      ArrayList<ArrayListRows> rowsArrayList = new ArrayList<ArrayListRows>();   
      for(int i = 0;i<rowsList.size();i++)   
      {   
          ArrayListRows temp = new ArrayListRows();   
          for(int j=0;j<(rowsList.get(i).coloumns.size());j++)   
          {   
              temp.coloumns.add(rowsList.get(i).coloumns.get(tot.get(j)));   
          }   
          rowsArrayList.add(temp);   
      }   
      return rowsArrayList;      
  }   
  public ArrayList<Integer> compareHeadings(ArrayListRows firstRowList1,ArrayListRows firstRowList2)   
  {   
      ArrayList<Integer> tot = new ArrayList<Integer>();   
      if(!(firstRowList1.coloumns.size() == firstRowList2.coloumns.size()))   
      {   
        System.out.println("cannot merge the files");   
        System.exit(0);   
        //return null;   
      }   
      System.out.println(firstRowList1.coloumns);   
      System.out.println(firstRowList2.coloumns);   
     for(int i=0;i<firstRowList1.coloumns.size();i++)   
      {   
         for(int j=0;j<firstRowList2.coloumns.size();j++)   
          {   
                  if((firstRowList1.coloumns.get(i).trim()).equals((firstRowList2.coloumns.get(j).trim())))   
                      {   
                        tot.add(j);   
                       break;   
                      }   
          }   
      }   
     return tot;   
  }   
  public ArrayList<ArrayListRows> addRows(ArrayList<ArrayListRows> rowsArrayList, ArrayList<ArrayListRows> rowsArrayList1 )   
  {   
      ArrayList<ArrayListRows> arrayRows = new ArrayList<ArrayListRows>();   
      Iterator<ArrayListRows> itera = rowsArrayList.iterator();   
      while(itera.hasNext())   
      {   
          arrayRows.add(itera.next());   
      }   
  
     for(int i=0;i<rowsArrayList1.size();i++)   
      {   
          int j;   
         for( j=0;j<rowsArrayList.size();j++)   
         {   
             if(compareColumns(rowsArrayList1.get(i), rowsArrayList.get(j)))   
                     {   
                        break;   
                     }   
                        
         }   
         if(j>=rowsArrayList1.size())   
                arrayRows.add(rowsArrayList1.get(i));   
      }     
      return arrayRows;   
  }   
  public boolean compareColumns(ArrayListRows row1,ArrayListRows row2)   
  {   
      for(int i=0;i<row1.coloumns.size();i++)   
      {   
      if(!row1.coloumns.get(i).equals(row2.coloumns.get(i)))   
          return false;   
      }   
  return true;   
            
  }   
  
  public ArrayList<ArrayListRows> getObjectsFromWorkBook(Workbook wb)   
  {   
      ArrayList<ArrayListRows> arrayRows = new ArrayList<ArrayListRows>();   
        Sheet sheet=null;              
       Row row=null;   
        Cell cell=null;   
           
        if(wb!=null){   
            sheet=wb.getSheetAt(0);   
            row=null;   
            cell=null;   
            Iterator<Row> rows=sheet.rowIterator();   
            while(rows.hasNext())   
            {   
                ArrayListRows allo = new ArrayListRows();   
                row=(Row)rows.next();                  
                Iterator<Cell> cells=row.cellIterator();   
                   
                while(cells.hasNext())   
                {   
                cell=( Cell)cells.next();   
                if(cell.getCellType()==Cell.CELL_TYPE_STRING){   
                        allo.coloumns.add(cell.getStringCellValue());   
                           
                }   
                else  
                    allo.coloumns.add(""+cell.getNumericCellValue());      
                }   
                arrayRows.add(allo);   
                   
            }   
        }   
      return arrayRows;   
  }   
  public  Workbook checkFileFormat(String fileName){   
        Workbook hwb=null;   
        FileInputStream checkFis=null;   
        try{   
             checkFis=new FileInputStream(fileName);   
             //Instantiate the Workbook using HSSFWorkbook   
             hwb=new HSSFWorkbook(checkFis);   
             Sheet sheet=hwb.getSheetAt(0);   
             Iterator<Row> rows=sheet.rowIterator();   
               
             Iterator<Cell> cells=null;   
             Row row=null;   
             Cell cell=null;   
             int check=0;   
             //Read the file as HSSFWorkbook   
             while(rows.hasNext()){   
                check++;   
                row=(HSSFRow)rows.next();   
                cells=row.cellIterator();   
                while(cells.hasNext()){   
                    cell=(HSSFCell)cells.next();   
                }   
                if(check==2)   
                    break;   
            }   
            //Return HSSFWorkbook type object if there is no exception in reading the file using HSSFWorkbook   
            return hwb;   
        }catch(ClassCastException ce){  //Instantiate the Workbook using XSSFWorkbook in case of class cast exception   
            Workbook xwb=null;   
            //System.out.println("class cast");   
            try{   
            xwb=new XSSFWorkbook(checkFis);        
            checkFis.close();   
            }catch(IOException e){   
            e.printStackTrace();   
            //System.out.println("class cast io");   
        }   
        return xwb; }   
        catch(Exception e){ //Instantiate the Workbook using XSSFWorkbook in case of Exception while reading file through HSSFWorkbook   
        Workbook xwb=null;   
        try{   
        checkFis.close();   
        checkFis=null;   
        checkFis=new FileInputStream(fileName);   
        xwb=new XSSFWorkbook(checkFis);    
        checkFis.close();   
        }catch(IOException ie){   
        ie.printStackTrace();   
  
    }   
           
    return xwb;   
    }   
    }   
}   
  
  
  
  
  
  
  
  
  
  
import java.util.ArrayList;   
  
public class ArrayListRows    
{   
   ArrayList<String> coloumns = new ArrayList<String>();   
   ArrayList<Integer> coloumnsType=new ArrayList<Integer>();   
      
}

[ Read More ]
Read more...
Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Use a StreamTokenizer object to parse a string separated by commas
     Use a StreamTokenizer object to parse a string entered from the keyboard containing a series of data items separated by commas and output ...
  • Singly linked list with header - Data Structure
    class OrderedList { private int value; private OrderedList next; // Note: No setValue() method or setNext() methods are provide...
  • Find File in a Zip File Example
    Find File in a Zip File Example. This Java example shows how to find a particular file in a zip file using ZipFile ...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • Creating Dynamic Macro Enabled Excel by Java
    We can create a dynamic macro enabled excel by java: We need to create a excel sheet template with macro on server. we can copy the...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • Printing Table In java using While Loop
    Here is a Java Program to Print the Table public class Table { public static void main(String[] args) { int no = Integer.p...
  • Java Class to Calculate the Volume of Box
    Here is a Java Class to Calculate the Volume of Box. class Box { double width; double height; double depth; // This is the con...
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger