@ApiOperation("批量导出商户档案")
@PostMapping(value = "/exportWord")
public void exportWordMerchantProfiles(@RequestBody ExportForm form, HttpServletResponse response) throws IOException, URISyntaxException {
List<Map<String, Object>> maps = new ArrayList<>();
List<String> filenames = new ArrayList<>();
for (String id : form.getIds()) {
PlaceInfo placeInfo = PlaceInfoService.selectPlaceInfoById(id);
if (placeInfo == null) continue;
Map<String, Object> map = placeInfo.convert();
String filename = map.get("unit_name") + "-商户档案.docx";
maps.add(map);
filenames.add(filename);
}
WordUtils.writeMultipleToResponse(templateFile, maps, filenames, response);
}
package com.yitu.common.utils.poi;
import com.deepoove.poi.XWPFTemplate;
import org.springframework.http.MediaType;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class WordUtils {
public static void writeToResponse(String path, Map<String, Object> map, String filename, HttpServletResponse response) throws URISyntaxException, IOException {
ServletOutputStream outputStream = getServletOutputStream(filename, response);
XWPFTemplate template = XWPFTemplate.compile(path).render(map);
template.write(outputStream);
template.close();
outputStream.flush();
}
public static void writeMultipleToResponse(String path, List<Map<String, Object>> mapList, List<String> filenames, HttpServletResponse response) throws IOException {
ServletOutputStream outputStream = getServletOutputStream("商户档案.zip", response);
try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
for (int i = 0; i < mapList.size(); i++) {
Map<String, Object> map = mapList.get(i);
String filename = filenames.get(i);
addToZip(zipOut, path, map, filename);
}
}
outputStream.flush();
}
private static void addToZip(ZipOutputStream zipOut, String path, Map<String, Object> map, String filename) throws IOException {
try (XWPFTemplate template = XWPFTemplate.compile(path).render(map)) {
ZipEntry zipEntry = new ZipEntry(filename);
zipOut.putNextEntry(zipEntry);
template.write(zipOut);
zipOut.closeEntry();
}
}
private static ServletOutputStream getServletOutputStream(String filename, HttpServletResponse response) throws IOException {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(filename, StandardCharsets.UTF_8.toString()) + "\"");
return response.getOutputStream();
}
}