首先是MAVEN依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
注意poi为XSL格式(03以及03以前) poi-ooxml为07以后的XLSX
public static void writeCountryListToFile(String fileName, ArrayList<ArrayList<String>> countryList) throws Exception{ //首先创建工作表 Workbook workbook = null; //随便初始化个数据 ArrayList<String> l1 = new ArrayList<>(); l1.add("广东"); l1.add("广州"); countryList.add(l1); ArrayList<String> l2 = new ArrayList<>(); l2.add("福建"); l2.add("福州"); countryList.add(l2); //判断文件的结尾名称来创建不同格式的文件 if(fileName.endsWith("xlsx")){ workbook = new XSSFWorkbook(); }else if(fileName.endsWith("xls")){ workbook = new HSSFWorkbook(); }else{ throw new Exception("invalid file name, should be xls or xlsx"); } //创建一个sheet 名字随便起 Sheet sheet = workbook.createSheet("SomeThing"); int rowIndex = 0; for (int i=0;i<countryList.size();i++) { List<String> ll= countryList.get(i); //创建一行 Row row = sheet.createRow(i); for (int j=0; j<ll.size();j++) { //创建一行的某个cell 定位(i,j) 和table的使用方式差不多 Cell cell = row.createCell(j); cell.setCellValue(ll.get(j)); } } //定义输出流,将workbook输出到文件 结束 FileOutputStream fos = new FileOutputStream(fileName); workbook.write(fos); fos.close(); System.out.println(fileName + " written successfully"); }
完~