Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.80 KB | None | 0 0
  1. package main;
  2.  
  3. import java.io.Closeable;
  4. import java.io.File;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.util.ArrayList;
  8. import org.apache.poi.ss.usermodel.Cell;
  9. import org.apache.poi.ss.usermodel.Row;
  10. import org.apache.poi.xssf.usermodel.XSSFSheet;
  11. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  12.  
  13. public class excelSheet{
  14.  
  15.  public static void main(String[] args) throws IOException {
  16.   writeFileUsingPOI();
  17.  }
  18.  
  19.  public static void writeFileUsingPOI() throws IOException
  20.  {
  21.   //create blank workbook
  22.   XSSFWorkbook workbook = new XSSFWorkbook();
  23.  
  24.   //Create a blank sheet
  25.   XSSFSheet sheet = workbook.createSheet("excelOne");
  26.  
  27.   ArrayList<Object[]> data=new ArrayList<Object[]>();
  28.   data.add(new String[]{"one","two","three"});
  29.   data.add(new Object[]{"IN","wkwk",10000});
  30.   data.add(new Object[]{"LN","wews",40000});
  31.   data.add(new Object[]{"GM","aall",20000});
  32.   data.add(new Object[]{"PR","sdoss",30000});
  33.  
  34.  
  35.   //Iterate over data and write to sheet
  36.   int rownum = 0;
  37.   for (Object[] countries : data)
  38.   {
  39.    Row row = sheet.createRow(rownum++);
  40.  
  41.    int cellnum = 0;
  42.    for (Object obj : countries)
  43.    {
  44.     Cell cell = row.createCell(cellnum++);
  45.     if(obj instanceof String)
  46.      cell.setCellValue((String)obj);
  47.     else if(obj instanceof Double)
  48.      cell.setCellValue((Double)obj);
  49.     else if(obj instanceof Integer)
  50.      cell.setCellValue((Integer)obj);
  51.    }
  52.   }
  53.   try
  54.   {
  55.    //Write the workbook in file system
  56.    FileOutputStream out = new FileOutputStream(new File("newfile.xlsx"));
  57.    workbook.write(out);
  58.    out.close();
  59.    System.out.println("CountriesDetails.xlsx has been created successfully");
  60.   }
  61.   catch (Exception e)
  62.   {
  63.    e.printStackTrace();
  64.   }
  65.   finally {
  66.    ((Closeable) workbook).close();
  67.   }
  68.  }
  69.  
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement