liujie
2025-11-24 2a6f08facd68df8fae5e43e3d9fbaa9e7237a7f5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package com.ruoyi.web.controller.api;
 
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.model.TPartyBuilding;
import com.ruoyi.system.query.PartyBuildingListQuery;
import com.ruoyi.system.service.TPartyBuildingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
 
import static com.ruoyi.web.controller.common.ExcelExportExample.example1;
 
@Slf4j
@RestController
@RequestMapping("/partyBuilding")
@Api(tags = "党建引领")
public class PartyBuildingController {
 
    private final TPartyBuildingService partyBuildingService;
 
    public PartyBuildingController(TPartyBuildingService partyBuildingService) {
        this.partyBuildingService = partyBuildingService;
    }
 
    @ApiOperation(value = "党建引领--列表",response = TPartyBuilding.class)
    @PostMapping(value = "/getPartyBuildingList")
    public R<Page<TPartyBuilding>> getPartyBuildingList(@RequestBody PartyBuildingListQuery query) {
        Page<TPartyBuilding> page = new Page<>(query.getPageNum(), query.getPageSize());
        Page<TPartyBuilding> pageTPartyBuilding = partyBuildingService.page(page,
                Wrappers.<TPartyBuilding>lambdaQuery()
                        .eq(TPartyBuilding::getPartyType, query.getPartyType())
                        .orderByDesc(TPartyBuilding::getCreateTime));
 
        return R.ok(pageTPartyBuilding);
    }
 
    @ApiOperation(value = "党建引领--详情",response = TPartyBuilding.class)
    @PostMapping(value = "/getPartyBuildingDetail/{id}")
    public R<TPartyBuilding> getPartyBuildingDetail(@PathVariable String id) {
        TPartyBuilding partyBuilding = partyBuildingService.getById(id);
        partyBuilding.setReadCount(partyBuilding.getReadCount() + 1);
        partyBuildingService.updateById(partyBuilding);
        return R.ok(partyBuilding);
    }
    // 默认模板路径 - 根据实际情况修改
    private static final String DEFAULT_TEMPLATE_PATH = "F:\\code\\mobile_community\\ruoyi-applet\\src\\main\\resources\\11.xlsx";
 
    /**
     * 导出Excel文件
     */
    @PostMapping("/excel")
    public ResponseEntity<?> exportExcel() {
        try {
            // 使用提供的模板路径或默认路径
            String templatePath =  DEFAULT_TEMPLATE_PATH;
 
            // 生成Excel文件字节数据
            byte[] excelData = createExcelFromTemplate(templatePath, generateTestData());
 
            // 创建资源对象
            ByteArrayResource resource = new ByteArrayResource(excelData);
 
            // 设置文件名
            String filename =  "export_data.xlsx";
 
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
 
 
        } catch (Exception e) {
            throw new RuntimeException("导出Excel文件失败: " + e.getMessage(), e);
        }
    }
 
    /**
     * 基于模板创建Excel文件
     */
    private byte[] createExcelFromTemplate(String templatePath, List<List<Object>> dataList)
            throws IOException {
 
        try (FileInputStream templateStream = new FileInputStream(templatePath);
             Workbook workbook = WorkbookFactory.create(templateStream);
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
 
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
 
            // 从第四行开始填充数据(行索引从0开始,第四行索引为3)
            fillDataToSheet(sheet, dataList, 3);
 
            // 写入输出流
            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }
 
    /**
     * 填充数据到工作表
     */
    private void fillDataToSheet(Sheet sheet, List<List<Object>> dataList, int startRowIndex) {
        if (dataList == null || dataList.isEmpty()) {
            return;
        }
 
        for (int i = 0; i < dataList.size(); i++) {
            Row row = sheet.createRow(startRowIndex + i);
            List<Object> rowData = dataList.get(i);
 
            // 确保每行有22列数据
            for (int j = 0; j < 22; j++) {
                Cell cell = row.createCell(j);
                Object value = j < rowData.size() ? rowData.get(j) : "";
                setCellValue(cell, value);
            }
        }
    }
 
    /**
     * 设置单元格值
     */
    private void setCellValue(Cell cell, Object value) {
        if (value == null) {
            cell.setCellValue("");
        } else if (value instanceof String) {
            cell.setCellValue((String) value);
        } else if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        } else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        } else if (value instanceof Boolean) {
            cell.setCellValue((Boolean) value);
        } else if (value instanceof Long) {
            cell.setCellValue((Long) value);
        } else {
            cell.setCellValue(value.toString());
        }
    }
 
    /**
     * 生成测试数据
     */
    private List<List<Object>> generateTestData() {
        List<List<Object>> dataList = new java.util.ArrayList<>();
 
        // 生成5行测试数据
        for (int i = 1; i <= 5; i++) {
            List<Object> row = new java.util.ArrayList<>();
 
            // 22列测试数据
            row.add("数据" + i + "-1");
            row.add("数据" + i + "-2");
            row.add(i * 100);
            row.add(i * 50.5);
            row.add(i % 2 == 0);
 
            // 填充剩余列
            for (int j = 5; j < 22; j++) {
                row.add("值" + i + "-" + (j + 1));
            }
 
            dataList.add(row);
        }
 
        return dataList;
    }
}