pom edition
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.7</version>
</dependency>1. Custom merge cells
In some business scenarios, there may be a need to merge cells , The following describes how to implement
1.1 Do not merge cells
Let's first look at the code for not merging cells , Simply review
public static void writeExcel() {
// Write excel The path of , Under the current project path
String fileName = getPath();
// structure ExcelWriter
ExcelWriter excelWriter = EasyExcel.write(fileName).excelType(ExcelTypeEnum.XLSX).build();
// structure sheet
WriteSheet writeSheet = EasyExcel.writerSheet(" Templates 1").head(DemoData.class).build();
// Write sheet
excelWriter.write(data1(), writeSheet);
excelWriter.finish();
}
private static String getPath() {
return System.getProperty("user.dir") + "/" + System.currentTimeMillis() + ".xlsx";
}
private static List<DemoData> data1() {
List<DemoData> list = Lists.newArrayList();
for (int i = 0; i < 3; i++) {
DemoData data = new DemoData();
data.setString(" character string " + 1);
data.setDate(new Date());
data.setDoubleData(0.56);
list.add(data);
}
for (int i = 0; i < 3; i++) {
DemoData data = new DemoData();
data.setString(" character string " + 2);
data.setDate(new Date());
data.setDoubleData(0.56);
list.add(data);
}
for (int i = 0; i < 4; i++) {
DemoData data = new DemoData();
data.setString(" character string " + 3);
data.setDate(new Date());
data.setDoubleData(0.57);
list.add(data);
}
return list;
}
public static void main(String[] args) {
writeExcel();
}Turn on the output of excel The following is the end of the document , You can see that the cells are not merged . Now I'm going to merge the first column with the same string title

1.2 merge cell
// Custom merge policy This class inherits AbstractMergeStrategy Abstract merge strategy , Need to rewrite merge() Method
public static class CustomMergeStrategy extends AbstractMergeStrategy {
/**
* grouping , Merge every few lines
*/
private List<Integer> exportFieldGroupCountList;
/**
* Target merge column index
*/
private Integer targetColumnIndex;
// You need to start merging the first row of cells index
private Integer rowIndex;
// exportDataList Is the value of the target column to be merged
public CustomMergeStrategy(List<String> exportDataList, Integer targetColumnIndex) {
this.exportFieldGroupCountList = getGroupCountList(exportDataList);
this.targetColumnIndex = targetColumnIndex;
}
@Override
protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
if (null == rowIndex) {
rowIndex = cell.getRowIndex();
}
// Merge only from the cells in the first row and the target column , Ignore the others
if (cell.getRowIndex() == rowIndex && cell.getColumnIndex() == targetColumnIndex) {
mergeGroupColumn(sheet);
}
}
private void mergeGroupColumn(Sheet sheet) {
int rowCount = rowIndex;
for (Integer count : exportFieldGroupCountList) {
if(count == 1) {
rowCount += count;
continue ;
}
// merge cell
CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCount, rowCount + count - 1, targetColumnIndex, targetColumnIndex);
sheet.addMergedRegionUnsafe(cellRangeAddress);
rowCount += count;
}
}
// In this method, the target columns can be merged continuously according to whether the values are the same , Store the number of rows that can be merged
private List<Integer> getGroupCountList(List<String> exportDataList){
if (CollectionUtils.isEmpty(exportDataList)) {
return new ArrayList<>();
}
List<Integer> groupCountList = new ArrayList<>();
int count = 1;
for (int i = 1; i < exportDataList.size(); i++) {
if (exportDataList.get(i).equals(exportDataList.get(i - 1))) {
count++;
} else {
groupCountList.add(count);
count = 1;
}
}
// After processing the last item
groupCountList.add(count);
return groupCountList;
}
}
// modify WriteSheet The code for is as follows
public static void writeExcel() {
String fileName = getPath();
ExcelWriter excelWriter = EasyExcel.write(fileName).excelType(ExcelTypeEnum.XLSX).build();
List<DemoData> demoDataList = data1();
// Write sheet Register the corresponding custom merge cell policy
WriteSheet writeSheet = EasyExcel.writerSheet(" Templates 1").head(DemoData.class)
.registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(DemoData::getString).collect(Collectors.toList()), 0))
.build();
excelWriter.write(demoDataList, writeSheet);
excelWriter.finish();
}Turn on the output of excel The following is the end of the document , You can see that the cells with the same value in the first column have been merged , Successful implementation

Similarly, if you want to merge the data in the third column , You can register a sheet Write processor , The code is as follows
public static void writeExcel() {
String fileName = getPath();
ExcelWriter excelWriter = EasyExcel.write(fileName).excelType(ExcelTypeEnum.XLSX).build();
List<DemoData> demoDataList = data1();
WriteSheet writeSheet = EasyExcel.writerSheet(" Templates 1").head(DemoData.class)
.registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(DemoData::getString).collect(Collectors.toList()), 0))
.registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(o -> o.getDoubleData().toString()).collect(Collectors.toList()), 2))
.build();
excelWriter.write(demoDataList, writeSheet);
excelWriter.finish();
}excel Open as follows :

1.3 Write more than one sheet
public static void writeExcel() {
String fileName = getPath();
ExcelWriter excelWriter = EasyExcel.write(fileName).excelType(ExcelTypeEnum.XLSX).build();
List<DemoData> demoDataList = data1();
WriteSheet writeSheet = EasyExcel.writerSheet(" Templates 1").head(DemoData.class)
.registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(DemoData::getString).collect(Collectors.toList()), 0))
.registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(o -> o.getDoubleData().toString()).collect(Collectors.toList()), 2))
.build();
excelWriter.write(demoDataList, writeSheet);
WriteSheet writeSheet1 = EasyExcel.writerSheet(" Templates 2").head(DemoData.class).build();
excelWriter.write(data1(), writeSheet1);
excelWriter.finish();
}Output excel You can see that there are already two sheet 了

1.4 WriteTable
If the business requirements are in the same sheet Write multiple tables in , It needs to be used WriteTable 了 . Define only one WriteSheet, A few tables define just a few WriteTable
public static void writeExcel01() {
String fileName = getPath();
ExcelWriter excelWriter = EasyExcel.write(fileName).excelType(ExcelTypeEnum.XLSX).build();
WriteSheet writeSheet = EasyExcel.writerSheet(" Templates ").needHead(Boolean.FALSE).build();
List<DemoData> demoDataList = data1();
// The header should be set to true,WriteTable Some attributes are inherited from WriteSheet
WriteTable writeTable = EasyExcel.writerTable(1).head(DemoData.class).needHead(Boolean.TRUE)
.registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(DemoData::getString).collect(Collectors.toList()), 0))
.registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(o -> o.getDoubleData().toString()).collect(Collectors.toList()), 2))
.build();
excelWriter.write(demoDataList, writeSheet, writeTable);
WriteTable writeTable1 = EasyExcel.writerTable(2).head(DemoData.class).needHead(Boolean.TRUE).build();
excelWriter.write(data1(), writeSheet, writeTable1);
excelWriter.finish();
}open excel Form the following

Conclusion
If there are errors or optimization points, please point them out , This article references from EasyExcel file
EasyExcel- More about merging cells
- C# obtain Excel Merge cells in
C# obtain Excel Merge cells in When we make the form , Sometimes you often need to merge and Unmerge some cells . When you cancel merging cells, you need to find and cancel one by one , More trouble . Here's a simple way to identify Excel Merge cells in , Identify this ...
- jquery Operation form merge cell
jquery operation table, merge cell , Merge the same lines Method of merger $("#tableid").mergeCell({ cols:[X,X] /// The parameter is the column to merge }) /** * ...
- NPOI operation EXCEL( 5、 ... and )—— Contains a complex header of merged cells EXCEL analysis
In the third article, we talked about the very anti human excel Templates , In order to support the family , I also tried my best to make the corresponding analytical method ... Let's take a look at the first type of complex header : ...... Bloggers say this kind of excel The template is a slightly complex header template ( Blue section ...
- poi Gets the value of the first row and first column in the merged cell
When reading as shown in the figure excel when , It is shown as 1 That's ok The first 1 Column The content is : merge cell Other cells in the merged cell range are not displayed The sample code is as follows : import java.io.FileInputStream; impo ...
- Repeater Multiple columns merge cells separately
GridView.Repeater Merging cells can refer to http://www.cnblogs.com/zhmore/archive/2009/04/22/1440979.html, But the original example is a combined column ...
- Aspose.Cells For the first time to use , Use templates to fill in data , merge cell , Line break
Aspose.Cells For the first time to use , Use templates to fill in data , merge cell , Line break Template format , Graph format is the simplest format , But the actual effect is not this , The actual effect is shown in the picture 2 chart 2 , Pay attention to the red part , One on one is normal , But there are one to many orders ...
- easyui datagrid merge cell
Sort out what you've done before , The problem of merging cells has been written in Sina blog ..... The following code is the list data // Load emission factor management report data function LoadEmissionReportData() { // a ...
- GRIDVIEW Merge cells with multiple rows and columns ( Merge Columns )
GitHub Project address :https://github.com/mingceng/merge-gridviewcell Last year , I wrote two articles : GridView Merge cells with multiple rows and columns ( Complete code and examples ) ...
- C# export Excel, And set up Excel Format cells , merge cell .
notes : You want to add COM Components Microsoft Excel 11.0 Object Library quote . The specific code is as follows : using System; using System.Collections.G ...
- Merge cells with complex headers HtmlTable convert to DataTable And export Excel
step : One . The front desk JS take HtmlTable data , Put the data together according to the set separator <!-- export Excel--> <script type="text/javascript&qu ...
Random recommendation
- 【 There must be a surprise 】android How programmers do their own API Interface ?php And android Good interaction ( Attached environment construction ), Let the front end data move ~
One . Write it at the front web Development can be divided into front end and back end , Actually android There are still front-end and back-end .android Development is the equivalent of mobile phones app The front end of the , It's usually php+android perhaps jsp+android Development .androi ...
- sql Three dimensional data
There is a steel project importing data today Inventory specifications are various Hematemesis The original table structure is like this code . specifications . name Three inventories All three have the same specifications Specifications are divided into thickness and width So here comes the question A few simple thicknesses and widths Three commodities That's it 10 ...
- About Javascript In language this keyword ( Variable ) Usage of
A lot of these days Javascript Beginners' friends are always asking : Javascript Of this Keyword usage . Here I simply summarize this Keyword usage . this Keyword is an important concept in object-oriented programming language ! stay J ...
- browser css How to hide the scroll bar ! except IE Generally speaking, they support
::-webkit-scrollbar { /* The whole part of the scroll bar */ width:0px; margin-right:2px}::-webkit-scrollbar-track-piece { /* ...
- mysql Develop advanced series 11 The lock problem ( The need for recovery and replication , Impact on the locking mechanism )
1. The need for recovery and replication , Yes innodb The influence of locking mechanism mysql adopt binlog The file is used to add, delete, change and other updated data sql sentence , Realize database recovery and master-slave replication .mysql The recovery mechanism ( Replication is in fact slave mys ...
- C++/C#: class Class And the structure Struct The difference between
C++ in : Default access control . Inherited access permissions are different :struct when public Of ,class when private Of : The rest is basically the same . C# in : struct Value type ,class Is of reference type : struct S ...
- Linux File system introduction and the difference between soft link and hard link
Linux With an extremely rich file system , It can be divided into the following categories : Network file system : Such as nfs.cifs etc. : Disk file system : Such as ext3.ext4 etc. : Special file systems : Such as prco.sysfs.ramfs.tmpfs etc. : ...
- Oracle Memory structure
Memory structure Oracle Memory , Process and database diagram sga: System global area , Data used to store operations , Library cache , Memory area of control information such as data dictionary , pga: Process global area , Memory area dedicated to the service process , Most content is not shared uga: use ...
- find Find... By time , Detailed explanation
https://blog.csdn.net/u010181136/article/details/73322738 find is aix/linux More maintenance commands are used on , But many times, it is necessary to use time - specific ...
- KMP Algorithmic pattern matching
Reprint please indicate the source http://blog.csdn.net/pony_maggie/article/details/37832707 author : The pony Finding a substring in a long string is a more common operation . Various information retrieval ...

![[ctfshow 单身杯]web writeup&&学习一下sed awk基本用法](/img/e6/c0ce483e091ba03f81667dacc04c3b.png)






