POM文件

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi-ooxml</artifactId>
  4. <version>3.12</version>
  5. </dependency>

示例代码

  1. package com.yue.test.tool;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.util.Map;
  6. import java.util.Set;
  7. import java.util.TreeMap;
  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. public class WriterExcel {
  13. public static void main(String[] args) throws IOException {
  14. // 1. 创建工作簿
  15. XSSFWorkbook workbook = new XSSFWorkbook();
  16. // 2. 创建工作表
  17. XSSFSheet sheet = workbook.createSheet("WriterDataTest");
  18. // 3. 模拟待写入数据
  19. Map<String, Object[]> data = new TreeMap<>();
  20. data.put("1", new Object[] { "ID", "NAME", "LASTNAME" });
  21. data.put("2", new Object[] { 1, "Amit", "Shukla" });
  22. data.put("3", new Object[] { 2, "Lokesh", "Gupta" });
  23. data.put("4", new Object[] { 3, "John", "Adwards" });
  24. data.put("5", new Object[] { 4, "Brian", "Schultz" });
  25. // 4. 遍历数据写入表中
  26. Set<String> keySet = data.keySet();
  27. int rowNum = 0;
  28. for (String key : keySet) {
  29. Row row = sheet.createRow(rowNum++);
  30. Object[] objArr = data.get(key);
  31. int cellNum = 0;
  32. for (Object obj : objArr) {
  33. Cell cell = row.createCell(cellNum++);
  34. if (obj instanceof String) {
  35. cell.setCellValue((String) obj);
  36. } else if (obj instanceof Integer) {
  37. cell.setCellValue((Integer) obj);
  38. }
  39. }
  40. }
  41. try {
  42. File file = new File("C:\\Users\\YueWang\\eclipse-workspace\\Test.xlsx");
  43. FileOutputStream out = new FileOutputStream(file);
  44. workbook.write(out);
  45. } catch (Exception e) {
  46. e.printStackTrace();
  47. } finally {
  48. workbook.close();
  49. }
  50. }
  51. }