Excel函数的命令行执行

时间:2015-01-08 15:41:26

标签: linux windows excel command-line

可以从命令行调用Excel函数吗?

我不想与任何文件进行任何互动。我想像其他命令行工具一样使用这些功能。它应该仅用于一些一次性目的。

例如,我喜欢它,如果有办法做这样的事情:

$ excel roman(15)
XV

$ excel randbetween(10,20)
14

当然,并非所有可用的功能都可以像这样运行,但越多越好。

  1. 是否存在任何本机应用程序(在Linux或Windows上,但最好是跨平台) 提供这种选择?

  2. 或者我们有什么方法可以操纵excel本身来做到这一点 (尽管根据我搜索过的内容,这似乎并非如此 可能)?

3 个答案:

答案 0 :(得分:2)

libformula可能是个好地方。这是概念证明:

$ excel 'TRIM(" abc 123  ")'
abc 123

其中excel是这个简单的shell脚本:

#!/bin/sh

java -cp /usr/share/java/commons-logging.jar:libformula/demo:libbase/dist/libbase-6.1-SNAPSHOT.jar:libformula/dist/libformula-6.1-SNAPSHOT.jar:/home/cwarden/git/excel/src org.xerus.excel.Excel "$1"

org.xerus.excel.Excel从argv获取一个字符串并将其作为公式计算:

package org.xerus.excel;

import org.pentaho.reporting.libraries.formula.EvaluationException;
import org.pentaho.reporting.libraries.formula.Formula;
import org.pentaho.reporting.libraries.formula.DefaultFormulaContext;
import org.pentaho.reporting.libraries.formula.parser.ParseException;

public class Excel {
        public static void main(final String[] args) throws ParseException, EvaluationException {
                final Formula f = new Formula(args[0]);
                f.initialize(new DefaultFormulaContext());
                final Object o = f.evaluate();
                System.out.println(o);
        }
}

libformula包含一个演示程序org.pentaho.reporting.libraries.formula.demo.PrintAllFunctions,它打印出所有支持的函数:

Category User-Defined
ARRAYCONCATENATE, ARRAYCONTAINS, ARRAYLEFT, ARRAYMID, CSVARRAY, CSVTEXT, NORMALIZEARRAY, NULL, PARSEDATE, SEQUENCEQUOTER
Category Information
CHOOSE, COUNT, COUNTA, COUNTBLANK, ERROR, HASCHANGED, INDEX, ISBLANK, ISERR, ISERROR, ISEVEN, ISLOGICAL, ISNA, ISNONTEXT, ISNUMBER, ISODD, ISREF, ISTEXT, LOOKUP, NA, VALUE
Category Rounding
INT
Category Mathematical
ABS, ACOS, ACOSH, ASIN, ATAN, ATAN2, AVERAGE, AVERAGEA, COS, EVEN, EXP, LN, LOG10, MAX, MAXA, MIN, MINA, MOD, N, ODD, PI, POWER, SIN, SQRT, SUM, SUMA, VAR
Category Text
ARRAYRIGHT, ASC, CHAR, CLEAN, CODE, CONCATENATE, EXACT, FIND, FIXED, FIXED, LEFT, LEN, LOWER, MESSAGE, MID, PROPER, REPLACE, REPT, RIGHT, SEARCH, STRINGCOUNT, SUBSTITUTE, T, TEXT, TRIM, UNICHAR, UNICODE, UPPER, URLENCODE
Category Date/Time
DATE, DATEDIF, DATETIMEVALUE, DATEVALUE, DAY, DAYS, HOUR, MINUTE, MONTH, MONTHEND, NOW, PREVWEEKDAY, SECOND, TIME, TIMEVALUE, TODAY, WEEKDAY, YEAR, YESTERDAY
Category Logical
AND, FALSE, IF, IFNA, NOT, OR, TRUE, XOR
Category Database
BEGINSWITH, CONTAINS, ENDSWITH, EQUALS, IN, LIKE

答案 1 :(得分:1)

这可以使用Apache POI Java API for Microsoft文档在Java中完成。在内存中创建Excel工作表,从命令行读取公式,然后打印结果。

以下程序执行此操作:

package stackoverflow.excel.formula;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Main {

    public static void main(String[] args) {
        String formula = args[0];

        // Create a cell and load the formula.
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellFormula(formula);

        // Evaluate the formula.
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
        CellValue cellValue = evaluator.evaluate(cell);
        switch (cellValue.getCellType()) {
        case Cell.CELL_TYPE_BOOLEAN:
            System.out.println(cellValue.getBooleanValue());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            System.out.println(cellValue.getNumberValue());
            break;
        case Cell.CELL_TYPE_STRING:
            System.out.println(cellValue.getStringValue());
            break;
        default: 
            break;
        }
    }

}

用于构建和打包程序的简单Maven pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>stackoverflow</groupId>
  <artifactId>excel_formula_cli</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <description>https://stackoverflow.com/questions/27843945/command-line-execution-of-excel-functions</description>

  <dependencies>
      <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi-ooxml</artifactId>
          <version>3.9</version>
      </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.2</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>stackoverflow.excel.formula.Main</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>


</project>

样本用法:

使用mvn clean package构建代码并使用java -jar target/excel_formula_cli-0.0.1-SNAPSHOT.jar "YOUR FORMULA HERE"

执行

这样做的缺点是并不支持所有Excel功能。例如,ROMAN()函数未实现。

java -jar target/excel_formula_cli-0.0.1-SNAPSHOT.jar "6*7" =&gt; 42.0

java -jar target/excel_formula_cli-0.0.1-SNAPSHOT.jar "roman(15)" =&gt; org.apache.poi.ss.formula.eval.NotImplementedException:ROMAN

java -jar target/excel_formula_cli-0.0.1-SNAPSHOT.jar "randbetween(10,20)" =&gt; 19.0

如果您对Apache POI公式支持的限制感到满意,这将提供可移植的跨平台解决方案。有关支持的功能列表,请参阅Developing Formula Evaluation - Appendix A

答案 2 :(得分:0)

一种方法是将脚本(VBScript或其他脚本环境)编写为:

  1. 打开Excel实例(不可见)
  2. 将您的字符串附加到“=”符号
  3. 将公式存入单元格
  4. 计算工作表
  5. 将结果显示给用户
  6. 关闭Excel的实例

    这将需要安装Excel或可以访问OneDrive。