package com.syngo.manage.util
import com.alibaba.excel.ExcelWriter
import com.alibaba.excel.support.ExcelTypeEnum
import com.alibaba.excel.write.metadata.WriteSheet
import com.alibaba.excel.write.metadata.WriteWorkbook
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.VerticalAlignment
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import javax.servlet.http.HttpServletResponse
import java.net.URLEncoder
import java.util.Collections
public class ExcelUtil {
private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class)
public static ExcelWriter getWriter(HttpServletResponse response, String fileName) {
try {
String encodedFileName = URLEncoder.encode(fileName, "UTF-8")
response.setCharacterEncoding("UTF-8")
response.setHeader("Content-Type", "application/vnd.ms-excel")
response.setHeader("Content-Disposition",
"attachment
response.setContentType("application/vnd.ms-excel")
WriteWorkbook writeWorkbook = new WriteWorkbook()
writeWorkbook.setOutputStream(response.getOutputStream())
writeWorkbook.setExcelType(ExcelTypeEnum.XLS)
writeWorkbook.setAutoCloseStream(false)
return new ExcelWriter(writeWorkbook)
} catch (Exception ex) {
logger.error(ex.getMessage())
response.reset()
return null
}
}
public static WriteSheet getSimpleWriteSheet(String sheetName, Class<?> clazz) {
WriteCellStyle headCellStyle = new WriteCellStyle()
headCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER)
headCellStyle.setVerticalAlignment(VerticalAlignment.CENTER)
headCellStyle.setWrapped(false)
WriteCellStyle contentCellStyle = new WriteCellStyle()
contentCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER)
contentCellStyle.setVerticalAlignment(VerticalAlignment.CENTER)
contentCellStyle.setWrapped(true)
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headCellStyle, contentCellStyle)
WriteSheet sheet = new WriteSheet()
sheet.setSheetName(sheetName)
sheet.setClazz(clazz)
sheet.setCustomWriteHandlerList(Collections.singletonList(horizontalCellStyleStrategy))
return sheet
}
}