package com.cdkj.sys.service.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import com.cdkj.frame.core.dao.BaseDao;
import com.cdkj.frame.core.dao.impl.BaseServiceImpl;
import com.cdkj.frame.core.utils.TimeUtil;
import com.cdkj.frame.core.utils.ZipUtils;
import com.cdkj.sys.domain.vo.ExcelInfoBean;
import com.cdkj.sys.service.ExcelService;
/**
*
* Excel操作服务类
*
*/
@Service
public class ExcelServiceImpl extends BaseServiceImpl implements ExcelService {
private final static DecimalFormat df00 = new DecimalFormat("_00");
private final static String TEMP = "/download/excel/tmp/";
private String rootRealPath;
@Override
public String array2Excel(String sheetName, List
rows, int totalCol, String[] headers) throws Exception {
XSSFWorkbook workbook = null;
try{
StringBuffer filePath = new StringBuffer(getRootRealPath());
String relativeFile = TEMP + createFileName(0);
String excelPath = filePath.append(relativeFile).toString();
createExcelFile(excelPath);
workbook = new XSSFWorkbook();
XSSFCellStyle headerStyle = getHeaderStyle(workbook);
XSSFCellStyle dataStyle = getDataStyle(workbook);
XSSFSheet sheet = null;
if(rows.size() > LIMIT_SIZE){
sheet = workbook.createSheet(sheetName + "0");
}else{
sheet = workbook.createSheet(sheetName);
}
//生成Excel标题
createHeader(sheet, totalCol, headers, headerStyle);
int sheetRowIdx = 0;
int rowIdx = 0;
for(ExcelInfoBean rowInfo : rows){
sheetRowIdx++;
rowIdx++;
createDataRow(sheet, sheetRowIdx, totalCol, rowInfo, dataStyle);
if(sheetRowIdx%LIMIT_SIZE == 0){
if(rowIdx < rows.size()){
sheet = workbook.createSheet(sheetName+(rowIdx/LIMIT_SIZE));
sheetRowIdx = 0;
createHeader(sheet, totalCol, headers, headerStyle);
}
}
}
FileOutputStream excelOutStream = new FileOutputStream(excelPath);
workbook.write(excelOutStream);
excelOutStream.flush();
excelOutStream.close();
return relativeFile;
}finally{
if(workbook != null){
workbook.close();
}
}
}
@Override
protected BaseDao getBaseDao() {
return null;
}
/**
* 返回以\结尾的物理路径
* @return
* {@code} D:\..\sqjz421\
*/
public String getRootRealPath() {
if(StringUtils.isBlank(rootRealPath)){
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
rootRealPath = webApplicationContext.getServletContext().getRealPath("/");
}
return rootRealPath;
}
/**
*
* @param sheet
* @param sheetRowIdx 页内行号
* @param totalCol 总列数
* @param rowInfo 行数据
* @return
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
*/
private XSSFRow createDataRow(XSSFSheet sheet, int sheetRowIdx, int totalCol, ExcelInfoBean rowInfo, XSSFCellStyle style) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
XSSFRow row = sheet.createRow(sheetRowIdx);
for(int j = 1; j <= totalCol; j++){
String val = BeanUtils.getProperty(rowInfo, "c" + j);
XSSFCell cell = row.createCell(j - 1);
cell.setCellValue(val);
if(style != null){
cell.setCellStyle(style);
}
}
return row;
}
/**
*
* @param sheet
* @param sheetRowIdx
* @param totalCol
* @param rowInfo
* @return
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
*/
protected XSSFRow createDataRow(XSSFSheet sheet, int sheetRowIdx, int totalCol, ExcelInfoBean rowInfo) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
return createDataRow(sheet, sheetRowIdx, totalCol, rowInfo, null);
}
/**
* 生成Excel标题行
* @param sheet
* @param totalCol
* @param headers
* @return
*/
protected XSSFRow createHeader(XSSFSheet sheet, int totalCol, String[] headers){
return this.createHeader(sheet, totalCol, headers, null);
}
/**
*
* @param sheet
* @param totalCol
* @param headers
* @param style 标题样式
* @return
*/
protected XSSFRow createHeader(XSSFSheet sheet, int totalCol, String[] headers, XSSFCellStyle style){
XSSFRow row = sheet.createRow(0);
row.setHeightInPoints(2*sheet.getDefaultRowHeightInPoints());
for(int j = 0; j < totalCol; j++){
XSSFCell cell = row.createCell(j);
cell.setCellValue(headers[j]);
if(style != null){
cell.setCellStyle(style);
}
}
return row;
}
/**
* 获取随机文件名
* idx为0的时候不输出
* @param fileIdx
* @return yyyyMMddHHmmssSSS + random(4位) + _idx + .xlsx
*/
public String createFileName(int fileIdx) {
StringBuffer sb = new StringBuffer();
sb.append(TimeUtil.getYyyyMMddHHmmssSSS());
//四位随机数
String rondom = String.valueOf(new Random().nextInt(10000));
while (rondom.length() < 4) {
rondom = "0" + rondom;
}
sb.append(rondom);
if(fileIdx > 0){
sb.append(df00.format(fileIdx));
}
sb.append(".xlsx");
return sb.toString();
}
@Override
public File array2Excels(String zipName, List rows, int totalCol, String[] headers)
throws Exception {
XSSFWorkbook workbook = null;
XSSFCellStyle headerStyle = null;
XSSFCellStyle dataStyle = null;
File zip = null;
List zipSrcFiles = new ArrayList();
try{
StringBuffer filePath = new StringBuffer(getRootRealPath());
int fileIdx = 1;
if(rows.size() > LIMIT_SIZE){
fileIdx = 1;
}else{
fileIdx = 0;
}
String relativeFile = TEMP + createFileName(fileIdx);
String excelPath = filePath.append(relativeFile).toString();
zipSrcFiles.add(createExcelFile(excelPath));
workbook = new XSSFWorkbook();
headerStyle = getHeaderStyle(workbook);
dataStyle = getDataStyle(workbook);
XSSFSheet sheet = workbook.createSheet();
//生成Excel标题
createHeader(sheet, totalCol, headers, headerStyle);
int sheetRowIdx = 0;
int rowIdx = 0;
for(ExcelInfoBean rowInfo : rows){
sheetRowIdx++;
rowIdx++;
createDataRow(sheet, sheetRowIdx, totalCol, rowInfo, dataStyle);
if(sheetRowIdx%LIMIT_SIZE == 0){
write(workbook, excelPath);
if(rowIdx < rows.size()){
relativeFile = TEMP + createFileName(rowIdx/LIMIT_SIZE + 1);
filePath.setLength(0);
filePath.append(getRootRealPath());
excelPath = filePath.append(relativeFile).toString();
zipSrcFiles.add(createExcelFile(excelPath));
workbook = new XSSFWorkbook();
headerStyle = getHeaderStyle(workbook);
dataStyle = getDataStyle(workbook);
sheet = workbook.createSheet();
//生成Excel标题
createHeader(sheet, totalCol, headers, headerStyle);
}
sheetRowIdx = 0;
}
}
if(sheetRowIdx > 0){
write(workbook, excelPath);
}
//打包导出的excel文件
if(zipSrcFiles.size()>0){
String zipPath = getRootRealPath() + TEMP + zipName + TimeUtil.getYyyyMMddHHmmssSSS()+".zip";
zip = new File(zipPath);
ZipUtils.zip(zipSrcFiles, zip);
}
return zip;
}finally{
if(workbook != null){
workbook.close();
}
}
}
/**
* 创建Excel文件
* @param excelPath
* @throws IOException
*/
private File createExcelFile(String excelPath) throws IOException{
File excelFile = new File(excelPath);
if(!excelFile.exists()){
if(!excelFile.getParentFile().exists()){
excelFile.getParentFile().mkdirs();
}
excelFile.createNewFile();
}
return excelFile;
}
protected void write(XSSFWorkbook workbook, String excelPath) throws IOException{
FileOutputStream excelOutStream = new FileOutputStream(excelPath);
workbook.write(excelOutStream);
excelOutStream.flush();
excelOutStream.close();
workbook.close();
}
protected void write(XSSFWorkbook workbook, File excelPath) throws IOException{
FileOutputStream excelOutStream = new FileOutputStream(excelPath);
workbook.write(excelOutStream);
excelOutStream.flush();
excelOutStream.close();
workbook.close();
}
/**
* 应用标题样式
* @param sheet
* @param headerStyle
*/
protected void applyHeaderStyle(XSSFSheet sheet, XSSFCellStyle headerStyle){
XSSFRow header = sheet.getRow(0);
header.setHeightInPoints(2*sheet.getDefaultRowHeightInPoints());
header.setRowStyle(headerStyle);
for (int i = 0; i < header.getLastCellNum(); i++) {
header.getCell(i).setCellStyle(headerStyle);
}
}
@Override
public XSSFCellStyle getHeaderStyle(XSSFWorkbook workbook){
XSSFCellStyle headerStyle = workbook.createCellStyle();
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
headerStyle.setWrapText(true);
return headerStyle;
}
@Override
public XSSFCellStyle getDataStyle(XSSFWorkbook workbook){
XSSFCellStyle dataStyle = workbook.createCellStyle();
XSSFFont font = workbook.createFont();
font.setFontName("宋体");
font.setCharSet(XSSFFont.DEFAULT_CHARSET);
font.setFontHeightInPoints((short)9);
dataStyle.setFont(font);
dataStyle.setBorderBottom(BorderStyle.THIN);
dataStyle.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());
dataStyle.setBorderLeft(BorderStyle.THIN);
dataStyle.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());
dataStyle.setBorderRight(BorderStyle.THIN);
dataStyle.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());
dataStyle.setBorderTop(BorderStyle.THIN);
dataStyle.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex());
return dataStyle;
}
}