Guest User

Untitled

a guest
Mar 8th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. package excel;
  2.  
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7.  
  8. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  9. import org.apache.poi.ss.usermodel.Cell;
  10. import org.apache.poi.ss.usermodel.CellStyle;
  11. import org.apache.poi.ss.usermodel.Font;
  12. import org.apache.poi.ss.usermodel.IndexedColors;
  13. import org.apache.poi.ss.usermodel.Row;
  14. import org.apache.poi.ss.usermodel.Sheet;
  15. import org.apache.poi.ss.usermodel.Workbook;
  16. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  17.  
  18. public class ExcelWriter {
  19.  
  20. private static String[] columns = { "First Name", "Last Name", "Email",
  21. "Date Of Birth" };
  22. private static List<Contact> contacts = new ArrayList<Contact>();
  23.  
  24. public static void main(String[] args) throws IOException,
  25. InvalidFormatException {
  26. contacts.add(new Contact("Sylvain", "Saurel",
  27. "sylvain.saurel@gmail.com", "17/01/1980"));
  28. contacts.add(new Contact("Albert", "Dupond",
  29. "sylvain.saurel@gmail.com", "17/08/1989"));
  30. contacts.add(new Contact("Pierre", "Dupont",
  31. "sylvain.saurel@gmail.com", "17/07/1956"));
  32. contacts.add(new Contact("Mariano", "Diaz", "sylvain.saurel@gmail.com",
  33. "17/05/1988"));
  34.  
  35. Workbook workbook = new XSSFWorkbook();
  36. Sheet sheet = workbook.createSheet("Contacts");
  37.  
  38. Font headerFont = workbook.createFont();
  39. headerFont.setBold(true);
  40. headerFont.setFontHeightInPoints((short) 14);
  41. headerFont.setColor(IndexedColors.RED.getIndex());
  42.  
  43. CellStyle headerCellStyle = workbook.createCellStyle();
  44. headerCellStyle.setFont(headerFont);
  45.  
  46. // Create a Row
  47. Row headerRow = sheet.createRow(0);
  48.  
  49. for (int i = 0; i < columns.length; i++) {
  50. Cell cell = headerRow.createCell(i);
  51. cell.setCellValue(columns[i]);
  52. cell.setCellStyle(headerCellStyle);
  53. }
  54.  
  55. // Create Other rows and cells with contacts data
  56. int rowNum = 1;
  57.  
  58. for (Contact contact : contacts) {
  59. Row row = sheet.createRow(rowNum++);
  60. row.createCell(0).setCellValue(contact.firstName);
  61. row.createCell(1).setCellValue(contact.lastName);
  62. row.createCell(2).setCellValue(contact.email);
  63. row.createCell(3).setCellValue(contact.dateOfBirth);
  64. }
  65.  
  66. // Resize all columns to fit the content size
  67. for (int i = 0; i < columns.length; i++) {
  68. sheet.autoSizeColumn(i);
  69. }
  70.  
  71. // Write the output to a file
  72. FileOutputStream fileOut = new FileOutputStream("contacts.xlsx");
  73. workbook.write(fileOut);
  74. fileOut.close();
  75. }
  76.  
  77. }
Add Comment
Please, Sign In to add comment