1、添加依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency>
2、java代码
public class CreateExcel { static String fileName = "work1.xsl"; /** * 读取domain文件的属性名和类型 * @param object * @return */ public static List<Map<String, String>> getDomainV(Object object){ List<Map<String, String>> result = new ArrayList<Map<String,String>> (); Field[] fields = object.getClass().getDeclaredFields(); for(int i=0;i<fields.length;i++){ Map<String, String> map = new HashMap<String, String>(); String attributeName = fields[i].getName(); //获取属性名称 String attributeType = fields[i].getGenericType().toString(); //获取属性类型 String[] types = attributeType.split("\."); map.put("name", attributeName); map.put("type", types[types.length-1]); result.add(map); } return result; } /** * 生成表格 * @param list * @throws IOException */ public static void createWorkBook(List<Map<String, String>> list,String fileName) throws IOException { Workbook wb = new HSSFWorkbook();//创建excel工作簿 Sheet sheet = wb.createSheet("new sheet"); //创建第一个sheet(页),命名为 new sheet for(int i=0;i<list.size();i++){ Row row = sheet.createRow(i); // 创建一行,在页sheet上 Cell cell = row.createCell(0); // 在row行上创建一个方格 cell.setCellValue(list.get(i).get("name")); //设置方格的显示 cell = row.createCell(1); cell.setCellValue(list.get(i).get("type")); // } FileOutputStream fileOut = new FileOutputStream(fileName); wb.write(fileOut); fileOut.close(); } /** * 读取Excel表格 * @param fileName * @throws Exception */ public static void readWorkBook(String fileName) throws Exception { InputStream inp = new FileInputStream(fileName); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { //利用foreach循环 遍历sheet中的所有行 for (Cell cell : row) { //遍历row中的所有方格 System.out.print(cell.toString() + " "); //输出方格中的内容,以空格间隔 } System.out.println(); //每一个行输出之后换行 } inp.close(); //关闭输入流 } public static void main(String[] args) throws Exception { Student stu = new Student(); List<Map<String, String>> list = getDomainV(stu); createWorkBook(list,fileName); System.out.println("creat successful!"); readWorkBook(fileName); } }