Excel操作(一)——模擬從資料庫查詢資料轉換為Excel
阿新 • • 發佈:2021-01-22
簡單的例子,表中格式為預設,沒有合併單元格以及設定單元格樣式等操作。
Maven倉庫引入poi依賴
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency>
方法體
該方法引數為一個存放資料的List集合和標題字串陣列
public static void generateExcelByDBData(List<Student> stuList, String[] arr) throws IllegalAccessException, IOException { //利用反射獲取Student的欄位名 Field[] fields = Student.class.getDeclaredFields(); //建立Excel文件 XSSFWorkbook stuBook = new XSSFWorkbook(); //sheet對應一個工作頁 XSSFSheet firstSheet = stuBook.createSheet("firstSheet"); //下標為0的行開始 XSSFRow firstRow = firstSheet.createRow(0); XSSFCell[] firstCell = new XSSFCell[arr.length]; //建立標題 for (int i = 0; i < arr.length; i++) { firstCell[i] = firstRow.createCell(i); firstCell[i].setCellValue(arr[i]); } //將物件轉換為Map<String,String>型的map便於設值 List<Map<String, String>> data = new ArrayList<>(); for (int i = 0; i < stuList.size(); i++) { Map<String, String> map = new HashMap<>(); Student student = stuList.get(i); Field[] stuFields = student.getClass().getDeclaredFields(); for (Field field : stuFields) { field.setAccessible(true); String m = ""; if (field.get(student) != null) { m = field.get(student).toString(); } map.put(field.getName(), m); } data.add(map); } //將data裡的值賦給cell單元格 Map<String, String> dataMap; for (int i = 0; i < data.size(); i++) { //建立一行 XSSFRow row_now = firstSheet.createRow(firstSheet.getLastRowNum() + 1); dataMap = data.get(i); for (int j = 0; j < fields.length; j++) { XSSFCell col = row_now.createCell(j); col.setCellValue(dataMap.get(fields[j].getName())); } } OutputStream out = new FileOutputStream("d:/student.xlsx"); stuBook.write(out); out.close(); } }
Main方法中程式碼為
//模擬從資料庫查詢到的資料 //假設Student類的欄位作為表的標題 String[] arr = {"學號", "姓名", "年齡", "性別", "地址"}; List<Student> stuList = new ArrayList<>(); stuList.add(new Student(1, "張三", 20, "男", "湖北省武漢市江夏區金融港")); stuList.add(new Student(2, "李四", 22, "男", "湖北省武漢市江夏區金融港")); stuList.add(new Student(2, "於五", 23, "男", "湖北省武漢市江夏區金融港")); try { generateExcelByDBData(stuList, arr); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
執行程式碼,在目標地址生成.xlsx檔案
如圖