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
| import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy; import com.ilubov.util.EasyExcelUtil; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List;
@RequestMapping("/test") @RestController public class TestController {
// 只合并表头 @GetMapping("/export1") public void export1(HttpServletResponse response) throws IOException { List<List<String>> headList = Lists.newArrayList(); List<List<Object>> dataList = Lists.newArrayList(); String filename = "test"; for (int j = 1; j < 5; j++) { List<Object> data = Lists.newArrayList(); for (int i = 1; i < 10; i++) { if (j == 1) { String h1, h2 = String.format("head%s", i); if (i > 5) { h1 = String.format("head%s", 2); } else { h1 = String.format("head%s", 1); } headList.add(ImmutableList.of(h1, h2)); } data.add(i); } dataList.add(data); } EasyExcelUtil.export(response, headList, dataList, filename); }
// 合并表头并合并第一列相同单元格 @GetMapping("/export2") public void export2(HttpServletResponse response) throws IOException { List<List<String>> headList = Lists.newArrayList(); List<List<Object>> dataList = Lists.newArrayList(); String filename = "test"; for (int j = 1; j < 8; j++) { List<Object> data = Lists.newArrayList(); for (int i = 1; i < 10; i++) { if (j == 1) { String h1, h2 = String.format("head%s", i); if (i > 5) { h1 = String.format("head%s", 2); } else { h1 = String.format("head%s", 1); } headList.add(ImmutableList.of(h1, h2)); } if (i == 1) { data.add(j < 3 ? "A" : j < 5 ? "B" : "C"); } else { data.add(i); } } dataList.add(data); } EasyExcelUtil.export(response, headList, dataList, filename, this.merge(dataList)); }
// 合并第一列相同单元格 private List<OnceAbsoluteMergeStrategy> merge(List<List<Object>> dataList) { List<OnceAbsoluteMergeStrategy> strategyList = Lists.newArrayList(); int start = 2, end = 1; Object index, base = dataList.get(0).get(0); for (List<Object> objects : dataList) { index = objects.get(0); if (base.equals(index)) { end++; } else { base = index; if (end > start) { strategyList.add(new OnceAbsoluteMergeStrategy(start, end, 0, 0)); } start = end++ + 1; } } if (end > start) { strategyList.add(new OnceAbsoluteMergeStrategy(start, end, 0, 0)); } return strategyList; } }
|