Kaynağa Gözat

1.新增导出功能

WoNiu 4 yıl önce
ebeveyn
işleme
de7a07a3f6

+ 83 - 0
src/main/java/com/galaxis/manatee/controller/ExcelController.java

@@ -0,0 +1,83 @@
+package com.galaxis.manatee.controller;
+
+import com.galaxis.manatee.dao.ChuanyunUserDao;
+import com.galaxis.manatee.entity.chuanyun.data.object.ChuanyunUserDO;
+import com.galaxis.manatee.util.ExcelUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.List;
+
+@RestController
+@Slf4j
+public class ExcelController {
+
+    private final ChuanyunUserDao chuanyunUserDao;
+
+    public ExcelController(ChuanyunUserDao chuanyunUserDao) {
+        this.chuanyunUserDao = chuanyunUserDao;
+    }
+
+
+    @ResponseBody
+    @RequestMapping(value = "/test/exportExcel", method = RequestMethod.GET)
+    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
+        List<ChuanyunUserDO> list = chuanyunUserDao.findAll();
+        String[] title = {"ID", "姓名", "头像", "工号", "钉钉号"};
+        String filename = "testRecord.xls";
+        String sheetName = "sheet1";
+        String[][] content = new String[list.size()][7];
+        try {
+            for (int i = 0; i < list.size(); i++) {
+                content[i][0] = String.valueOf(list.get(i).getObjectId());
+                content[i][1] = list.get(i).getName();
+                content[i][2] = list.get(i).getPhoto();
+                content[i][3] = list.get(i).getEmployeeNumber();
+                content[i][4] = list.get(i).getDingTalkAccount();
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);
+        try {
+            // 响应到客户端
+            this.setResponseHeader(response, filename);
+            OutputStream os = response.getOutputStream();
+            wb.write(os);
+            os.flush();
+            os.close();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 向客户端发送响应流方法
+     *
+     * @param response
+     * @param fileName
+     */
+    public void setResponseHeader(HttpServletResponse response, String fileName) {
+        try {
+            try {
+                fileName = new String(fileName.getBytes(), "UTF-8");
+            } catch (UnsupportedEncodingException e) {
+                e.printStackTrace();
+            }
+            response.setContentType("application/vnd.ms-excel");
+            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
+        } catch (Exception ex) {
+            ex.printStackTrace();
+        }
+    }
+}

+ 3 - 0
src/main/java/com/galaxis/manatee/entity/chuanyun/data/object/ChuanyunUserDO.java

@@ -38,6 +38,9 @@ public class ChuanyunUserDO extends BasicDO{
      */
     @JsonProperty(value = "Title")
     private String title;
+    
+    
+    private String photo;
 
     /**
      * 工号

+ 99 - 6
src/main/java/com/galaxis/manatee/util/ExcelUtils.java

@@ -1,12 +1,11 @@
 package com.galaxis.manatee.util;
 
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
+import java.io.*;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
 import java.math.BigDecimal;
+import java.net.HttpURLConnection;
+import java.net.URL;
 import java.net.URLEncoder;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -28,8 +27,7 @@ import org.apache.commons.lang.BooleanUtils;
 import org.apache.commons.lang.CharUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.lang.math.NumberUtils;
-import org.apache.poi.hssf.usermodel.HSSFDateUtil;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.hssf.usermodel.*;
 import org.apache.poi.ss.usermodel.Cell;
 import org.apache.poi.ss.usermodel.CellStyle;
 import org.apache.poi.ss.usermodel.Font;
@@ -52,6 +50,83 @@ public class ExcelUtils {
     private final static String EXCEL2003 = "xls";
     private final static String EXCEL2007 = "xlsx";
 
+
+    /**
+     * 导出Excel
+     *
+     * @param sheetName sheet名称
+     * @param title     标题
+     * @param values    内容
+     * @param wb        HSSFWorkbook对象
+     * @return
+     */
+    public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb) throws Exception {
+
+        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
+        if (wb == null) {
+            wb = new HSSFWorkbook();
+        }
+        // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
+        HSSFSheet sheet = wb.createSheet(sheetName);
+
+        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
+        HSSFRow row = sheet.createRow(0);
+
+        // 第四步,创建单元格,并设置值表头 设置表头居中
+        HSSFCellStyle style = wb.createCellStyle();
+        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
+
+        //声明列对象
+        HSSFCell cell = null;
+
+        //创建标题
+        for (int i = 0; i < title.length; i++) {
+            cell = row.createCell(i);
+            cell.setCellValue(title[i]);
+            cell.setCellStyle(style);
+        }
+
+        //创建内容
+        for (int i = 0; i < values.length; i++) {
+            row = sheet.createRow(i + 1);
+            for (int j = 0; j < values[i].length; j++) {
+                //生成图片
+                if (j==2){
+                    URL url = new URL(values[i][j]);
+                    //打开链接
+                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
+                    //设置请求方式为"GET"
+                    conn.setRequestMethod("GET");
+                    //超时响应时间为5秒
+                    conn.setConnectTimeout(5 * 1000);
+                    //通过输入流获取图片数据
+                    InputStream inStream = conn.getInputStream();
+                    //得到图片的二进制数据,以二进制封装得到数据,具有通用性
+                    byte[] data = readInputStream(inStream);
+                    //anchor主要用于设置图片的属性
+                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 250,(short) 2, i, (short) 3, i+1);
+                    //Sets the anchor type (图片在单元格的位置)
+                    //0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.
+                    anchor.setAnchorType(0);
+                    HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
+                    patriarch.createPicture(anchor, wb.addPicture(data, HSSFWorkbook.PICTURE_TYPE_PNG));
+                }else{
+                    //将内容按顺序赋给对应的列对象
+                    row.createCell(j).setCellValue(values[i][j]);
+                }
+            }
+        }
+        return wb;
+    }
+
+    /**
+     * 导入Excel
+     * @param path
+     * @param cls
+     * @param file
+     * @param <T>
+     * @return
+     */
     public static <T> List<T> readExcel(String path, Class<T> cls,MultipartFile file){
 
         String fileName = file.getOriginalFilename();
@@ -341,4 +416,22 @@ public class ExcelUtils {
             e.printStackTrace();
         }
     }
+
+
+    private static byte[] readInputStream(InputStream inStream) throws Exception{
+        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
+        //创建一个Buffer字符串
+        byte[] buffer = new byte[1024];
+        //每次读取的字符串长度,如果为-1,代表全部读取完毕
+        int len = 0;
+        //使用一个输入流从buffer里把数据读取出来
+        while( (len=inStream.read(buffer)) != -1 ){
+            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
+            outStream.write(buffer, 0, len);
+        }
+        //关闭输入流
+        inStream.close();
+        //把outStream里的数据写入内存
+        return outStream.toByteArray();
+    }
 }