Преглед на файлове

矛盾纠纷临时提交--第一次迁移--截止

wanghao преди 1 месец
родител
ревизия
84e98ba344
променени са 1 файла, в които са добавени 181 реда и са изтрити 0 реда
  1. 181 0
      src/main/java/org/ssssssss/example/datacheck/common/ExcelExportUtilBlob.java

+ 181 - 0
src/main/java/org/ssssssss/example/datacheck/common/ExcelExportUtilBlob.java

@@ -0,0 +1,181 @@
+package org.ssssssss.example.datacheck.common;
+
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.springframework.http.ResponseEntity;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.URLEncoder;
+import java.util.List;
+import java.util.Map;
+import org.springframework.core.io.InputStreamResource;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+
+public class ExcelExportUtilBlob {
+
+    /**
+     * 将查询结果导出为Excel并通过浏览器下载
+     *
+     * @param response    HttpServletResponse对象
+     * @param dataList     查询结果数据 List<Map<String, Object>>
+     * @param fileName     导出的文件名(不需要后缀)
+     * @param sheetName    Excel工作表名称
+     * @throws IOException 如果发生I/O错误
+     */
+    public static ResponseEntity<InputStreamResource> exportToExcel(HttpServletResponse response,
+                                                       List<Map<String, Object>> dataList,
+                                                       String fileName,
+                                                       String sheetName) throws IOException {
+        // 创建工作簿
+        Workbook workbook = new XSSFWorkbook(); //xlsx
+//        Workbook workbook = new HSSFWorkbook();  //xls
+
+        // 创建工作表
+        Sheet sheet = workbook.createSheet(sheetName != null ? sheetName : "Sheet1");
+
+        // 创建表头样式
+        CellStyle headerStyle = createHeaderCellStyle(workbook);
+
+        // 创建数据行样式
+        CellStyle dataStyle = createDataCellStyle(workbook);
+
+        // 如果数据不为空,处理数据
+        if (dataList != null && !dataList.isEmpty()) {
+            // 创建表头行
+            Row headerRow = sheet.createRow(0);
+
+            // 获取第一个Map的key集合作为表头
+            Map<String, Object> firstRow = dataList.get(0);
+            int colNum = 0;
+
+            // 写入表头
+            for (String key : firstRow.keySet()) {
+                Cell cell = headerRow.createCell(colNum++);
+                cell.setCellValue(key);
+                cell.setCellStyle(headerStyle);
+            }
+
+            // 写入数据
+            int rowNum = 1;
+            for (Map<String, Object> rowData : dataList) {
+                Row row = sheet.createRow(rowNum++);
+                colNum = 0;
+                for (String key : firstRow.keySet()) {
+                    Cell cell = row.createCell(colNum++);
+                    Object value = rowData.get(key);
+                    setCellValue(cell, value, dataStyle);
+                }
+            }
+
+            // 自动调整列宽
+            for (int i = 0; i < firstRow.size(); i++) {
+                sheet.autoSizeColumn(i);
+            }
+        }
+
+
+        // 设置响应头
+//        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
+
+        fileName = URLEncoder.encode(fileName+DateUtils.dateTimeNow(),"UTF-8");
+
+//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+//        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
+
+
+
+        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+        workbook.write(outputStream);
+        outputStream.flush();
+        workbook.close();
+
+        // 2. 转换为 InputStream
+        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
+
+        // 3. 返回流式响应
+        return ResponseEntity.ok()
+                .header("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+                .header("Content-Disposition", "attachment; filename=" + fileName + ".xlsx")
+                .body(new InputStreamResource(inputStream));
+
+
+
+
+    }
+
+    /**
+     * 创建表头单元格样式
+     */
+    private static CellStyle createHeaderCellStyle(Workbook workbook) {
+        CellStyle style = workbook.createCellStyle();
+        Font font = workbook.createFont();
+        font.setBold(true);
+        font.setFontHeightInPoints((short) 12);
+        style.setFont(font);
+        style.setAlignment(HorizontalAlignment.CENTER);
+        style.setVerticalAlignment(VerticalAlignment.CENTER);
+        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
+        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
+        style.setBorderTop(BorderStyle.THIN);
+        style.setBorderBottom(BorderStyle.THIN);
+        style.setBorderLeft(BorderStyle.THIN);
+        style.setBorderRight(BorderStyle.THIN);
+        return style;
+    }
+
+    /**
+     * 创建数据单元格样式
+     */
+    private static CellStyle createDataCellStyle(Workbook workbook) {
+        CellStyle style = workbook.createCellStyle();
+        style.setAlignment(HorizontalAlignment.LEFT);
+        style.setVerticalAlignment(VerticalAlignment.CENTER);
+        style.setBorderTop(BorderStyle.THIN);
+        style.setBorderBottom(BorderStyle.THIN);
+        style.setBorderLeft(BorderStyle.THIN);
+        style.setBorderRight(BorderStyle.THIN);
+        style.setWrapText(true);
+        return style;
+    }
+
+    /**
+     * 根据值的类型设置单元格的值
+     */
+    private static void setCellValue(Cell cell, Object value, CellStyle style) {
+        cell.setCellStyle(style);
+
+        if (value == null) {
+            cell.setCellValue("");
+        } else if (value instanceof String) {
+            cell.setCellValue((String) value);
+        } else if (value instanceof Number) {
+            if (value instanceof Integer || value instanceof Long ||
+                    value instanceof Short || value instanceof Byte) {
+                cell.setCellValue(((Number) value).doubleValue());
+            } else if (value instanceof Double || value instanceof Float) {
+                cell.setCellValue(((Number) value).doubleValue());
+            } else {
+                cell.setCellValue(value.toString());
+            }
+        } else if (value instanceof Boolean) {
+            cell.setCellValue((Boolean) value);
+        } else if (value instanceof java.util.Date) {
+            cell.setCellValue((java.util.Date) value);
+        } else if (value instanceof java.sql.Date) {
+            cell.setCellValue(new java.util.Date(((java.sql.Date) value).getTime()));
+        } else if (value instanceof java.sql.Timestamp) {
+            cell.setCellValue(new java.util.Date(((java.sql.Timestamp) value).getTime()));
+        } else {
+            cell.setCellValue(value.toString());
+        }
+    }
+}