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(); } } }
|