报表导出jxls的使用笔记

2019-04-30 23:41:09来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

基于poi的jxls工具的使用:
1.依赖:

<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-poi</artifactId>
<version>1.0.16</version>
<exclusions>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</exclusion>
</exclusions>
</dependency>

2.代码:
2.1业务类:
/**
* 目标sheet索引
*/
String TARGET_SHEET_INDEX = "_targetSheetIndex";

/**
* 目标sheet名称
*/
String TARGET_SHEET_NAME = "_targetSheetName";
public void exportFile(HttpServletResponse response) throws  Exception {
// 获取模板目录
String templateFilePath = OrdersExportTemplateFilePath;
if (StringUtils.isEmpty(templateFilePath)) {
}
templateFilePath = templateFilePath.trim();
InputStream fileInputStream = null;
try {
// 读取文件
fileInputStream = FileReader.readFile(templateFilePath);
String fileNameWithPrefix ="渠道分析报表"+"-"+ DateUtil.getDateTimeStrT(new Date()) +".xlsx";
String mimeType = URLConnection.guessContentTypeFromName(fileNameWithPrefix);
if (mimeType == null) {
//unknown mimetype so set the mimetype to application/octet-stream
mimeType = "application/octet-stream;charset=UTF-8";
}
response.setContentType(mimeType);
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileNameWithPrefix,"UTF-8") );
// 查询数据
List<BaiduTongjiData> list = getStatisticsData("20190401","20190501");
// 导出
Map<String, Object> beans = new HashMap<>();
// 目标sheet名称
beans.put(UtilKeyName.TARGET_SHEET_NAME, "订单导出列表!A1");
// 目标sheet索引
beans.put(UtilKeyName.TARGET_SHEET_INDEX, 1);
beans.put("data", list);
beans.put("indexUpdater", new OrderExportCellUpdater.IndexCellUpdater());
JxlsUtil.exportExcel(fileInputStream, response.getOutputStream(), beans);
} finally {
if (fileInputStream != null) {
fileInputStream.close();
}
}
}


2.2工具类

public class JxlsUtil {

private static final Logger logger = LoggerFactory.getLogger(JxlsUtil.class);

static {
// 添加自定义指令
XlsCommentAreaBuilder.addCommandMapping("merge", MergeCommand.class);
}

/**
* jxls模版文件目录
*/
private final static String TEMPLATE_PATH = "templates";

/**
* 导出Excel
*
* @param is 模板文件输入流
* @param os 生成文件输出流
* @param beans 填充数据
* @throws IOException IO异常
*/
public static void exportExcel(InputStream is, OutputStream os, Map<String, Object> beans) throws IOException, InvalidFormatException {
if (beans == null) {
return;
}
Workbook workbook = WorkbookFactory.create(is);
// setting rowAccessWindowSize to 600 to be able to process static cells in a single iteration
Transformer transformer = PoiTransformer.createSxssfTransformer(workbook, 600, true);
// 不打印警告信息
JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
evaluator.getJexlEngine().setSilent(true);

AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer);
List<Area> areaList = areaBuilder.build();
Area area = areaList.get(0);
// 定义上下文
Context context = new PoiContext(beans);
// 设置不处理公式
context.getConfig().setIsFormulaProcessingRequired(false);

Object targetSheetName = beans.get(UtilKeyName.TARGET_SHEET_NAME);
if (targetSheetName == null) {
logger.warn("Could not find 'TARGET_SHEET_NAME' in beans,set to empty String.");
targetSheetName = "";
}
Object targetSheetIndex = beans.get(UtilKeyName.TARGET_SHEET_INDEX);
if (targetSheetIndex == null) {
logger.warn("Could not find 'TARGET_SHEET_INDEX' in beans,set to 1.");
targetSheetIndex = "1";
}

area.applyAt(new CellRef((String) targetSheetName), context);
// 强制重新计算公式
workbook.setForceFormulaRecalculation(true);
// 定位到第一个sheet
workbook.setActiveSheet((Integer) targetSheetIndex);


// 删除模板sheet
workbook.removeSheetAt(0);
// 输出文件
((PoiTransformer) transformer).getWorkbook().write(os);
}


/**
* 导出Excel压缩包
*
* @param is 模板文件输入流
* @param fileName 唯一标志
* @param beans 填充数据
* @param excelTmpDir 导出excel文件的临时目录
* @throws IOException IO异常
*/
public static boolean createExcel(InputStream is, Map<String, Object> beans, String fileName, String excelTmpDir) {
if (beans == null) {
return false;
}
Workbook workbook = null;
try {
workbook = WorkbookFactory.create(is);
// setting rowAccessWindowSize to 600 to be able to process static cells in a single iteration
Transformer transformer = PoiTransformer.createSxssfTransformer(workbook, 600, true);
// 不打印警告信息
JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
evaluator.getJexlEngine().setSilent(true);

AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer);
List<Area> areaList = areaBuilder.build();
Area area = areaList.get(0);
// 定义上下文
Context context = new PoiContext(beans);
// 设置不处理公式
context.getConfig().setIsFormulaProcessingRequired(false);

Object targetSheetName = beans.get(UtilKeyName.TARGET_SHEET_NAME);
if (targetSheetName == null) {
logger.warn("Could not find 'TARGET_SHEET_NAME' in beans,set to empty String.");
targetSheetName = "";
}
Object targetSheetIndex = beans.get(UtilKeyName.TARGET_SHEET_INDEX);
if (targetSheetIndex == null) {
logger.warn("Could not find 'TARGET_SHEET_INDEX' in beans,set to 1.");
targetSheetIndex = "1";
}

area.applyAt(new CellRef((String) targetSheetName), context);
// 强制重新计算公式
workbook.setForceFormulaRecalculation(true);
// 定位到第一个sheet
workbook.setActiveSheet((Integer) targetSheetIndex);

// 删除模板sheet
workbook.removeSheetAt(0);

//临时输出excel文件
File file = new File(excelTmpDir + fileName);
FileOutputStream fileOutputStream = null;

fileOutputStream = new FileOutputStream(file);
((PoiTransformer) transformer).getWorkbook().write(fileOutputStream);

fileOutputStream.close();

} catch (FileNotFoundException e) {
logger.info("order export cause an fileNotFoundException:{}", e);
return false;
} catch (IOException e) {
logger.info("order export cause an IOException:{}", e);
return false;
} finally {
try {
is.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
return true;
}


/**
* 导出Excel核心逻辑
* <p>TODO 能不能不保存到磁盘,直接填充模板返回WorkBook
*
* @param is 模板文件输入流
* @param beans 数据
* @return 处理完成的Workbook
* @throws IOException 读取模板文件时的IO异常
*/
private static Workbook exportCore(InputStream is, Map<String, Object> beans) throws IOException {
if (beans == null) {
return null;
}
//....
if (StringUtils.isBlank(beans.get(UtilKeyName.TARGET_SHEET_NAME) + "")) {
// 目标sheet名称
logger.warn("Could not find 'TARGET_SHEET_NAME' in beans,set to empty String.");
beans.put(UtilKeyName.TARGET_SHEET_NAME, "");
}
if (StringUtils.isBlank(beans.get(UtilKeyName.TARGET_SHEET_INDEX) + "")) {
// 目标sheet索引
logger.warn("Could not find 'TARGET_SHEET_INDEX' in beans,set to 1.");
beans.put(UtilKeyName.TARGET_SHEET_INDEX, 1);
}

String tempPath = checkTempFolder() + UUID.randomUUID();
File file = new File(tempPath);
logger.info("Saving temp excel file to {}.", file.getAbsolutePath());
OutputStream os = new FileOutputStream(file);

Workbook workbook = WorkbookFactory.create(is);
// setting rowAccessWindowSize to 600 to be able to process static cells in a single iteration
Transformer transformer = PoiTransformer.createSxssfTransformer(workbook);
// 不打印警告信息
// JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
//evaluator.getJexlEngine().setSilent(true);

AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer);
List<Area> areaList = areaBuilder.build();
Area area = areaList.get(0);
// 定义上下文
Context context = new PoiContext(beans);
// 设置不处理公式
context.getConfig().setIsFormulaProcessingRequired(false);
area.applyAt(new CellRef((String) beans.get(UtilKeyName.TARGET_SHEET_NAME)), context);
// 强制重新计算公式
workbook.setForceFormulaRecalculation(true);
// 定位到第一个sheet
workbook.setActiveSheet((Integer) beans.get(UtilKeyName.TARGET_SHEET_INDEX));
// 删除模板sheet
workbook.removeSheetAt(0);
// 输出文件
Workbook targetWookbook = ((PoiTransformer) transformer).getWorkbook();
targetWookbook.write(os);

return ExcelFileReadUtil.readExcelFile2007(new FileInputStream(file));
}


/**
* 本地临时目录
*
* @return 本地临时目录
*/
private static String checkTempFolder() {
String temporaryPath = TemporaryPathUtil.getGlobalTempPathStr() + "ExcelTemp/";
File saveFolder = new File(temporaryPath);
if (!saveFolder.exists()) {
boolean mkdirs = saveFolder.mkdirs();
}
return temporaryPath;
}


/**
* 导出Excel
* <p>注意:会关闭流
*
* @param xlsxFilePath 模板文件路径
* @param beans 填充数据
* @throws IOException IO异常
*/
public static Workbook exportExcel(String xlsxFilePath, Map<String, Object> beans) throws IOException {
try (InputStream inputStream = FileReader.readFile(xlsxFilePath)) {
return exportCore(inputStream, beans);
}
}

/**
* 导出Excel
* <p>注意:会关闭流
*
* @param inputStream 模板文件输入流
* @param beans 填充数据
* @throws IOException IO异常
*/
public static Workbook exportExcel(InputStream inputStream, Map<String, Object> beans) throws IOException {
try {
return exportCore(inputStream, beans);
} finally {
inputStream.close();
}
}

/**
* 导出Excel
*
* @param xlsPath 模板文件路径
* @param outPath 生成文件路径
* @param beans 填充数据
* @throws IOException IO异常
*/
public static void exportExcel(String xlsPath, String outPath, Map<String, Object> beans) throws IOException, InvalidFormatException {
String absolutePath = new File(xlsPath).getAbsolutePath();
try (InputStream is = FileReader.readFile(xlsPath); OutputStream os = new FileOutputStream(outPath)) {
exportExcel(is, os, beans);
}
}

/**
* 导出Excel
*
* @param xlsFile 模板文件
* @param outFile 生成文件
* @param beans 填充数据
* @throws IOException IO异常
*/
public static void exportExcel(File xlsFile, File outFile, Map<String, Object> beans) throws IOException, InvalidFormatException {
try (InputStream is = new FileInputStream(xlsFile); OutputStream os = new FileOutputStream(outFile)) {
exportExcel(is, os, beans);
}
}

/**
* 获取模板文件
*
* @param fileName 模板文件名
* @return 模板文件
*/
public static File getTemplateFile(String fileName) {
URL resourceUrl = JxlsUtil.class.getClassLoader().getResource(TEMPLATE_PATH);
if (resourceUrl == null) {
return null;
}
String templateFilePath = resourceUrl.getPath();
File templateFile = new File(templateFilePath, fileName);
return templateFile.exists() ? templateFile : null;
}

/**
* 删除07以上excel文件的工作表
*
* @param xlsFile 文件
* @param sheetIndex 要删除的sheet的索引
* @throws IOException
*/
public static void deleteXSSFSheet(File xlsFile, int sheetIndex) throws IOException {
InputStream is = new FileInputStream(xlsFile);
XSSFWorkbook workbook = new XSSFWorkbook(is);
OutputStream os = new FileOutputStream(xlsFile);
try {
workbook.removeSheetAt(sheetIndex);
workbook.write(os);
} finally {
is.close();
os.close();
}
}
}
3.模板文件的定义:注意定义的区域要比模板的区域要大,否则会报错

 


 


			   

原文链接:https://www.cnblogs.com/echoskk/p/10796659.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:并发编程之多线程基础篇及面试

下一篇:------------------java collection 集合学习 ----小白学习笔记