瀏覽代碼

增加文件导出公共方法

crazycat 2 年之前
父節點
當前提交
bd520e27ca
共有 2 個文件被更改,包括 59 次插入0 次删除
  1. 12 0
      pom.xml
  2. 47 0
      src/main/java/com/welampiot/utils/ExcelUtil.java

+ 12 - 0
pom.xml

@@ -145,6 +145,18 @@
             <artifactId>geodesy</artifactId>
             <version>1.1.3</version>
         </dependency>
+<!--    excel 处理-->
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi</artifactId>
+            <version>5.2.2</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-ooxml</artifactId>
+            <version>5.2.2</version>
+        </dependency>
+
 
     </dependencies>
 

+ 47 - 0
src/main/java/com/welampiot/utils/ExcelUtil.java

@@ -0,0 +1,47 @@
+package com.welampiot.utils;
+
+import org.apache.poi.xssf.usermodel.XSSFCell;
+import org.apache.poi.xssf.usermodel.XSSFRow;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.List;
+
+public class ExcelUtil {
+    public static String outExcel(List<String> titleList,List<List<String>> contentList){
+        XSSFWorkbook sheets = new XSSFWorkbook();
+        XSSFSheet sheet = sheets.createSheet();
+
+        // 创建表头,也就是第一行
+        XSSFRow row = sheet.createRow(0);
+        for (int i = 0; i < titleList.size(); i++) {
+            XSSFCell cell = row.createCell(i);
+            cell.setCellValue(titleList.get(i));
+        }
+
+        //创建表内容,从第二行开始
+        for (int i = 0; i < contentList.size(); i++) {
+            row = sheet.createRow(i + 1);
+            for (int j = 0; j < contentList.get(i).size(); j++) {
+                row.createCell(j).setCellValue(contentList.get(i).get(j));
+            }
+        }
+        long l = System.currentTimeMillis();
+        String filePath = "/upload/temp/"+l+".xls";
+        File file = new File(".."+filePath);
+        //将文件保存到指定的位置
+        try {
+            File file2 = new File("../upload/temp/");
+            if (!file2.exists()) file2.mkdirs();
+            sheets.write(new FileOutputStream(file));
+            System.out.println("写入成功");
+            sheets.close();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return filePath;
+    }
+}