تنفيذ محرك الحساب المخصص لتوسيع محرك الحساب الافتراضي لـ Aspose.Cells
Aspose.Cells يمتلك محرك حساب قوي يمكنه حساب معظم صيغ Microsoft Excel تقريبًا. على الرغم من ذلك، يسمح لك أيضًا بتوسيع محرك الحساب الافتراضي مما يمنحك قوة ومرونة أكبر.
يتم استخدام الخصائص والفئات التالية في تنفيذ هذه الميزة.
تنفيذ محرك الحساب المخصص
يقوم الكود التالي بتنفيذ محرك الحساب المخصص. ينفذ واجهة AbstractCalculationEngine التي تحتوي على طريقة واحدة فقط calculate(CalculationData data). يتم استدعاء هذه الطريقة لجميع الصيغ الخاصة بك. داخل هذه الطريقة، نقوم بالتقاط وظيفة TODAY وإضافة يوم واحد إلى تاريخ النظام. لذا إذا كان التاريخ الحالي هو 27/07/2023، فسوف يقوم المحرك المخصص بحساب TODAY() كـ 28/07/2023.
نموذج برمجة
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
public class CustomEngine extends AbstractCalculationEngine { | |
public void calculate(CalculationData data) { | |
if (data.getFunctionName().toUpperCase().equals("TODAY")) { | |
data.setCalculatedValue(CellsHelper.getDoubleFromDateTime(DateTime.getNow(), false) + 1.0); | |
} | |
} | |
public getProcessBuiltInFunctions() { return true; } | |
} | |
public static void main(String[] args) throws Exception { | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(ImplementCustomCalculationEngine.class); | |
Workbook workbook = new Workbook(); | |
Worksheet sheet = workbook.getWorksheets().get(0); | |
Cell a1 = sheet.getCells().get("A1"); | |
Style style = cell.getStyle(); | |
style.setNumber(14); | |
cell.setStyle(style); | |
a1.setFormula("=TODAY()"); | |
// Without Custom Engine, the value of cell A1 will be 20 | |
workbook.calculateFormula(); | |
System.out.println("Without Custom Engine Value of A1: " + a1.getStringValue()); | |
// With Custom Engine, the value of cell A1 will be 50 | |
CalculationOptions opts = new CalculationOptions(); | |
opts.setCustomEngine(new CustomEngine()); | |
workbook.calculateFormula(opts); | |
System.out.println("With Custom Engine Value of A1: " + a1.getStringValue()); | |
} |
النتيجة
يرجى التحقق من إخراج الوحدة لمثال الشفرة أعلاه ، يجب أن يكون قيمة (التاريخ والوقت) لـ A1 مع محرك مخصص بعد يوم واحد عن النتيجة بدون محرك مخصص.