import com.hikvision.hikadmin.util.DateUtil;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
/**
* @Description excel导出
*/
public class ExportExcel {
private static final Logger logger = LoggerFactory.getLogger(ExportExcel.class);
/**
* excel导出
*
* @param excelName excel名称
* @param titels 每列标题
* @param fields 标题所对应实体类中的字段
* @param data 数据(泛型是对应的实体类)
* @param response
*/
public static void export(String excelName, String[] titels, String[] fields, List<?> data, HttpServletResponse response) {
if (titels.length == 0 || fields.length == 0) return;
OutputStream os = null;
response.setContentType("application/x-excel;charset=UTF-8");
try {
response.setHeader("Content-disposition", "attachment; filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1")
+ DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") + ".xlsx");
os = response.getOutputStream();
XSSFWorkbook workBook = new XSSFWorkbook();
Sheet sheet = workBook.createSheet(excelName);
Row row = sheet.createRow(0);
Font f = workBook.createFont();
f.setBoldweight(Font.BOLDWEIGHT_BOLD);//字体加粗
f.setFontHeightInPoints((short) 13);//字体大小
//样式
CellStyle style = workBook.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);//左右居中
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//上下居中
style.setFont(f);
for (int i = 0; i < titels.length; i++) {
row.createCell(i).setCellValue(titels[i]);
row.getCell(i).setCellStyle(style);
sheet.setColumnWidth(i, titels[i].getBytes().length * 2 * 256);
}
for (int i = 0; i < data.size(); i++) {
Row r = sheet.createRow(i + 1);
Object object = data.get(i);
for (int j = 0; j < fields.length; j++) {
char[] chars = fields[j].toCharArray();
//判断首字母是否小写
if (Character.isLowerCase(chars[0])){
chars[0] -= 32;
}
Method m = object.getClass().getMethod("get" + String.valueOf(chars));
r.createCell(j).setCellValue(null == m.invoke(object) ? "" : String.valueOf(m.invoke(object)));
}
}
workBook.write(os);
} catch (Exception e) {
logger.error("Excel导出" + excelName + "失败 : " + e);
} finally {
if (os != null) {
try {
os.flush();
} catch (IOException e) {
logger.error("Excel导出" + excelName + "失败,强制清除输出流失败 : " + e);
}
IOUtils.closeQuietly(os);
}
}
}
}