1

我想在 Excel 表格单元格中创建一个进度条。我必须使用 Apache Poi 库,但我什至不知道如何开始。(类似这样,但使用 Java 库)http://www.tech-recipes.com/rx/35064/excel-2013-create-progress-bars/

我想我必须设置条件格式,但我确实知道它是如何工作的,而且我在任何地方都找不到解决方案……有人可以帮我吗?

提前致谢。

4

1 回答 1

1

正如您所建议的,我使用您的链接创建了一个示例 xlsx 并简单地重新创建了必要的 xml 结构,即将 xlsx 文件作为 zip 存档打开并查看xl/worksheets/sheet1.xml. 除了 poi-ooxml.jar,您还需要 ooxml-schemas-1.1.jar。

(使用 Libre Office 4.0、Excel Viewer 2010、POI 3.10-beta1 测试)

import java.io.FileOutputStream;
import java.lang.reflect.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;

public class Databar {
    public static void main(String[] args) throws Exception {
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet();
        for (int i=0; i<4; i++) {
            sheet.createRow(i).createCell(0).setCellValue(new int[]{12,38,93,42}[i]);
        }

        SheetConditionalFormatting cf = sheet.getSheetConditionalFormatting();
        XSSFConditionalFormattingRule xcfrule =
            (XSSFConditionalFormattingRule)cf.createConditionalFormattingRule("");

        Method m = XSSFConditionalFormattingRule.class.getDeclaredMethod("getCTCfRule");
        m.setAccessible(true);
        CTCfRule cfRule = (CTCfRule)m.invoke(xcfrule);
        cfRule.removeFormula(0); // cleanup

        cfRule.setType(STCfType.DATA_BAR);
        CTDataBar databar = cfRule.addNewDataBar();
        CTCfvo vfoMin = databar.addNewCfvo();
        vfoMin.setType(STCfvoType.NUM);
        vfoMin.setVal("0");
        CTCfvo vfoMax = databar.addNewCfvo();
        vfoMax.setType(STCfvoType.NUM);
        vfoMax.setVal("100");
        CTColor color = databar.addNewColor();
        color.setRgb(new byte[]{(byte)0xFF, 0x00, 0x00, (byte)0xFF});

        CellRangeAddress cra[] = {new CellRangeAddress(0, 3, 0, 0)};
        cf.addConditionalFormatting(cra, xcfrule);

        FileOutputStream fos = new FileOutputStream("databar-out.xlsx");
        wb.write(fos);
        fos.close();
    }
}
于 2013-09-09T21:14:12.253 回答