首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在HSSFWorkbook中设置活动单元

在HSSFWorkbook中设置活动单元
EN

Stack Overflow用户
提问于 2018-04-24 18:05:17
回答 1查看 994关注 0票数 3

我正在尝试使用ApachePOI3.17创建一个带有特定单元格的旧风格的Excel文档(HSSFWorkbook)。下面的代码非常难看(它使用反射和私有字段),但是完成了工作。

是否有更好的方法来实现同样的目标?

代码语言:javascript
复制
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;

import org.apache.poi.hssf.model.InternalSheet;
import org.apache.poi.hssf.record.SelectionRecord;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress8Bit;
import org.apache.poi.ss.util.CellAddress;

public class ExcelGeneratorDemo {

    public static void main(String[] args) throws IOException {
        writeExcelFile("D21");
    }

    private static void writeExcelFile(String activeCell) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        CellAddress address = new CellAddress(activeCell);
        setActiveCell(sheet, address);
        wb.write(new File(activeCell + ".xls"));
    }

    /**
     * Calling just {@code sheet.setActiveCell} has no effect when opening
     * the file with Microsoft Excel 2016.
     */
    private static void setActiveCell(HSSFSheet sheet, CellAddress address) {
        sheet.setActiveCell(address);

        // Following three private fields in a row cannot be the correct path.
        InternalSheet internalSheet = getField(sheet, "_sheet");
        SelectionRecord selection = getField(internalSheet, "_selection");
        CellRangeAddress8Bit[] ranges = getField(selection, "field_6_refs");

        ranges[0].setFirstColumn(address.getColumn());
        ranges[0].setLastColumn(address.getColumn());
        ranges[0].setFirstRow(address.getRow());
        ranges[0].setLastRow(address.getRow());
    }

    private static <T> T getField(Object obj, String fieldName) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return (T) field.get(obj);
        } catch (ReflectiveOperationException e) {
            throw new IllegalStateException(e);
        }
    }
}

关于HSSF的相似问题也有一些变通代码。它不使用反射,但它的变通代码也不是直进的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-03 16:09:50

这是一个POI中的bug高达3.17,已经在当前的开发版本中得到了修正。

一旦发布,它可能会在3.18中修复。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50008212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档