未创建Apache POI XSSF标头

时间:2016-07-26 17:56:26

标签: coldfusion apache-poi coldfusion-10

在我尝试使用xlsx创建时,我一直坚持创建标头。我能够创建一个包含行和合并单元格的文件,但标题似乎永远不会起作用。这就是我所拥有的:

var WorkBook = CreateObject( 
    "java",
    "org.apache.poi.xssf.usermodel.XSSFWorkbook"
).Init();

var Sheet = WorkBook.CreateSheet(
    JavaCast( "string", 'my sheetname' )
);

// create the default header if it doesn't exist
var header = sheet.getHeader(); // have also tried getEvenHeader() and getOddHeader()

header.setText('&LLeft Section');
// have also tried the following:
//header.setLeft('left header');
//header.setCenter('CENTER');
//header.setRight('right header');

// open the file stream
var FileOutputStream = CreateObject(
    "java",
    "java.io.FileOutputStream"
).Init(
    JavaCast( "string", filename )
);

// Write the workbook data to the file stream.
WorkBook.Write( 
    FileOutputStream 
);

// Close the file output stream.
FileOutputStream.Close();

当我运行此代码时,不会抛出任何错误。该文件已创建,可以打开而不会抛出任何错误,但不会显示任何标题。就像我说的,如果我创建行/单元而不是标题,那么这些是正确创建的。我错过了什么?

编辑: 正如Leigh在下面指出的那样,页眉/页脚在Excel中的含义与我对它们的看法不同(如在PDF中)。我在第一行上方添加一个标题显示它在第一行上方的方式被抛弃,并认为通过POI添加一个也可以做同样的事情。

1 个答案:

答案 0 :(得分:4)

(根据评论推荐,如果答案对下一个人有帮助的话)

愚蠢的问题,但你如何验证标题不存在?在Excel中,headers and footers should only be visible when printing (or in print preview mode)

  

...标题中的工作表上不显示页眉和页脚   视图 - 它们仅在页面布局视图和打印中显示   页。

FWIW,在我填充至少一个单元格之后,代码在CF10和11下可以正常工作(因此有些内容可以打印)。

Runnable Example on trycf.com

<cfscript>
    workBook = CreateObject( "java", "org.apache.poi.xssf.usermodel.XSSFWorkbook").Init();
    sheet = WorkBook.CreateSheet( JavaCast( "string", 'my sheetname' ) );
    header = sheet.getHeader(); // have also tried getEvenHeader() and getOddHeader()
    header.setText('&LLeft Section');
    // add some data so there is something to print
    sheet.createRow(0).createCell(0).setCellValue("sample value");
    // Using binary stream because trycf.com does not support files for security reasons
    baos = createObject("java", "java.io.ByteArrayOutputStream").init();
    // Write the workbook data to the binary stream
    workBook.write( baos );
    baos.close();
</cfscript>

<!--- CF10 lacks support for script version of cfcontent --->
<cfcontent type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    variable="#baos.toByteArray()#">