java - 在 HSSFWorkbook 中设置 Activity 单元格

标签 java apache-poi hssf

我正在尝试使用 Apache POI 3.17 创建一个带有预选特定单元格的旧式 Excel 文档 (HSSFWorkbook)。下面的代码真的很难看(它使用了反射和私有(private)字段)但是完成了工作。

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

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

A similar question关于 HSSF 也有一些解决方法代码。它不使用反射,但其解决方法代码也不是直截了当的。

最佳答案

这是一个bug in POI up to 3.17 , 已在当前开发版本中修复。

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

关于java - 在 HSSFWorkbook 中设置 Activity 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50008212/

相关文章:

java - Intellij IDEA 中 Apache POI 的依赖关系存在问题。不一致的错误

java - 如何在spring mvc中使用java导入xls和xlsx文件

java - 使用 @Query 'No converter found capable of converting from type XXX' 时出现错误 ("Select * from")

java - Apache POI : Indexed Color from AWT Color input

java - 如何在不使用collect函数的情况下有效地将rdd转换为list

java - 使用 itextpdf 将 .pptx 转换为 .pdf。汉字字符定位错误

java - 使用 Apache POI 获取行数

java - 如果超出最大行数,则使用 java 和 POIExcel util 创建额外的 excel 文件

java - 防止用户打开同一个 Web 应用程序的多个窗口

java - BufferedReader 和 Stream Line Java 8