根据easyexcel model 导出工具类
时间: 2023-09-08 08:15:11 浏览: 97
以下是一个基于EasyExcel的导出工具类示例:
```java
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
public class ExcelExportUtil {
/**
* 导出Excel
*
* @param response HttpServletResponse
* @param fileName 文件名
* @param sheetName sheet名称
* @param head 表头
* @param data 数据
*/
public static void export(HttpServletResponse response, String fileName, String sheetName,
List<List<String>> head, List<List<Object>> data) throws IOException {
// 设置响应头
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 构建writer
ExcelWriterBuilder writerBuilder = EasyExcel.write(response.getOutputStream());
// 设置样式
WriteCellStyle headStyle = new WriteCellStyle();
headStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
WriteCellStyle contentStyle = new WriteCellStyle();
contentStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headStyle, contentStyle);
// 创建sheet
ExcelWriterSheetBuilder sheetBuilder = writerBuilder.sheet(sheetName);
WriteSheet sheet = sheetBuilder.build();
// 创建表头和表格
WriteTable table = new WriteTable();
table.setHead(head);
table.setClazz(Object.class);
table.setAutoWidth(true);
// 写入数据
EasyExcel.write(response.getOutputStream(), Object.class)
.registerWriteHandler(styleStrategy)
.sheet(sheetName)
.table(table)
.doWrite(data);
}
}
```
使用示例:
```java
List<List<String>> head = Arrays.asList(
Arrays.asList("姓名", "年龄", "性别"),
Arrays.asList("Tom", "18", "男"),
Arrays.asList("Lucy", "20", "女")
);
List<List<Object>> data = Arrays.asList(
Arrays.asList("Tom", 18, "男"),
Arrays.asList("Lucy", 20, "女")
);
ExcelExportUtil.export(response, "test.xlsx", "Sheet1", head, data);
```
阅读全文