基于模板的形式导出Excel
1、Excel处理类中使用JSONArray或者JSONObject定义需要输出数据的模板方法:
需要使用到的jar:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.6</version>
</dependency>
public static JSONArray baseInfo() {
//name为Excel中输出的表头,value与数据库输出的字段名一致
JSONObject json = null;
JSONArray array = new JSONArray();
json = new JSONObject();
json.put("name","姓名");
json.put("value","studentName");
array.add(json);
json = new JSONObject();
json.put("name","年龄");
json.put("value","age");
array.add(json);
json = new JSONObject();
json.put("name","性别");
json.put("value","gender");
array.add(json);
json = new JSONObject();
json.put("name","联系方式");
json.put("value","studentPhone");
array.add(json);
return array;
}
2、Excel处理类中对数据进行处理
public void exportExcel(HSSFWorkbook book, int sheetNum, String sheetTitle, JSONArray columnsArr, List<Map<String, Object>> exportsList) throws Exception {
/* 生成一个表格*/
HSSFSheet sheet = book.createSheet(sheetTitle);
/* sheetNum为sheet页,从0开始,sheetTitle为sheet的名称 */
book.setSheetName(sheetNum, sheetTitle);
/* 1 设置样式*/
HSSFCellStyle cellStyle = book.createCellStyle();
for (int i = 0; i <= columnsArr.size(); i++) {
if (i == 0) {
sheet.setColumnWidth