导出excel通用模板(程序定义模板导出)
转载原文:https://www.jianshu.com/p/5c7b359a159c
如下代码,本方法主要用于程序定义模板格式,并导出文件。该方法将定义和创建分离,达到了一定解耦合,降低了开发复杂度。但是依然是程序定义模板,对模板的样式需要程序控制,没有达到将数据和样式分离的目的。
改良版,关于添加依赖之类的之前一篇文章里面有。
这篇是把之前的方法抽成通用模板。
一、添加一个实体类
package com.lencity.securitymanagementplatform.data.entity;
import java.util.List;
public class XlsData {
public static final int DATA_TYPE_INTEGER = 0;
public static final int DATA_TYPE_STRING = 1;
private List<String> titles;//表头
private List<Integer> types;//数据类型
private List<List<Object>> values;存表数据
public List<Integer> getTypes() {
return types;
}
public void setTypes(List<Integer> types) {
this.types = types;
}
public List<String> getTitles() {
return titles;
}
public void setTitles(List<String> titles) {
this.titles = titles;
}
public List<List<Object>> getValues() {
return values;
}
public void setValues(List<List<Object>> values) {
this.values = values;
}
}
二、创建一个service类
package com.lencity.securitymanagementplatform.service;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.stereotype.Service;
import com.lencity.securitymanagementplatform.data.entity.XlsData;
@Service
public class XlsService {
//写一个接口,哪个控制器需要加上导出excel功能就继承这个接口
public static interface IXlsOutputProcessor {
public XlsData processXlsData(Map<String, Object> condition);
}
//解析数据创建excel
public HSSFWorkbook createExcelData(IXlsOutputProcessor processor, Map<String, Object> condition) {
XlsData xlsData = processor.processXlsData(condition);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("统计表");// 创建一个excel表单
HSSFRow titleRow = sheet.createRow(0);
// 设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
sheet.setColumnWidth(1, 15 * 256);
sheet.setColumnWidth(3, 20 * 256