java - 使用 Apache POI 保留 Excel 标题中的图像

标签 java excel apache-poi

我正在尝试使用 Apache POI 3.6(最新)生成 Excel 报告。

由于 POI 对页眉和页脚生成的支持有限(仅限文本),因此我决定从已准备好页眉的空白 Excel 文件开始,并使用 POI 填充 Excel 单元格(参见问题 714172 )。

不幸的是,当使用 POI 打开工作簿并立即将其写入磁盘(没有任何单元格操作)时,标题似乎丢失了。

这是我用来测试此行为的代码:

public final class ExcelWorkbookCreator {

  public static void main(String[] args) {
    FileOutputStream outputStream = null;
    try {
      outputStream = new FileOutputStream(new File("dump.xls"));
      InputStream inputStream = ExcelWorkbookCreator.class.getResourceAsStream("report_template.xls");
      HSSFWorkbook workbook = new HSSFWorkbook(inputStream, true);
      workbook.write(outputStream);
    } catch (Exception exception) {
      throw new RuntimeException(exception);
    } finally {
      if (outputStream != null) {
        try {
          outputStream.close();
        } catch (IOException exception) {
          // Nothing much to do
        }
      }
    }
  }
}

最佳答案

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet    sheet    = new HSSFSheet();

Header header = sheet.getHeader() //get header from workbook's sheet
header.setCenter(HSSFHeader.font("COURIER", "Normal")+ HSSFHeader.fontSize((short) 15) + "Hello world" +new Date()); // set header with desire font style 

FileOutputStream fileOut = new FileOutputStream("C:\\book.xls");
workbook.write(fileOut);       

关于java - 使用 Apache POI 保留 Excel 标题中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2012433/

相关文章:

java - Hibernate使用单表继承

excel - VBA从一个工作簿复制并粘贴到另一个工作簿

Java:将 XML 内容写入 Excel 文件的 StringWriter

java - 内存不足,无法处理大型文本文件并将其写回 xml

java - 检查重叠 2 个定期约会?

java - FXtras 议程 : set allowDragging property for individual appointments instead of whole agenda

VBA Workbook.Open(File) 什么都不返回

python - 循环遍历 python 数组以匹配第二个数组中的多个条件,快速方法?

java - 如何获取XSSFSimpleShape对象的背景颜色?

java - Apache POI 获取 NPE 读取 xls 文件