为什么不能使用Apache POI“正确”隐藏Excel行?

时间:2017-09-13 11:13:51

标签: java excel apache-poi

为什么不能使用Apache POI(3.16)“正确”隐藏Excel行?可以调用(XSSFRow)row.setZeroHeight(),这也是Busy developer's guide推荐的内容。但是,这与以Excel方式隐藏行的方式不同。您可以使用相应的上下文菜单选项“隐藏”和“取消隐藏”行。

我认为设置行样式应该可行,但事实并非如此。在生成的Excel文件中,仍可以看到该行。

package de.mwe;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.Assert;
import org.testng.annotations.Test;


public class MWE {

@Test
public void testHidingRows() {
    final XSSFWorkbook wb = new XSSFWorkbook();
    String sname = "HideRowsTestSheet", cname = "TestName", cvalue = "TestVal";
    XSSFSheet sheet = wb.createSheet( sname );
    XSSFRow row = sheet.createRow( 0 );
    XSSFCell cell = row.createCell( (short) 0 );
    cell.setCellValue( cvalue );

    XSSFCellStyle hiddenRowStyle = wb.createCellStyle();
    hiddenRowStyle.setHidden( true );

    row.setRowStyle( hiddenRowStyle );
    Assert.assertTrue( row.getRowStyle().getHidden() );

    try (FileOutputStream fileOut = new FileOutputStream( new File( "target/PoiTestDrive.xlsx" ) )) {
        wb.write( fileOut );
    } catch ( IOException ex ) {
        ex.printStackTrace();
    }

    // does not work, resulting Excel file shows first row.

}

}

2 个答案:

答案 0 :(得分:1)

Busy developer's guide对于隐藏/取消隐藏行是正确的。但是有一点错误,因为隐藏一行必须是row.setZeroHeight(true);

Row.setZeroHeight(boolean)与隐藏行时Excel完全相同。它适用于HSSF以及XSSF。对于XSSF,它只是为行XML设置隐藏属性,请参阅XSSFRow.java

示例:

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;

public class CreateExcelHiddenRow {

 public static void main(String[] args) throws Exception {

  //Workbook wb = new HSSFWorkbook();
  Workbook wb = new XSSFWorkbook();

  Sheet sheet = wb.createSheet();

  for (int r = 0; r < 3; r++) {
   Row row = sheet.createRow(r);
   Cell cell = row.createCell(0);
   cell.setCellValue("Row " + (r+1));
  }

  Row row = sheet.getRow(1);
  row.setZeroHeight(true);

  //FileOutputStream out = new FileOutputStream("CreateExcelHiddenRow.xls");   
  FileOutputStream out = new FileOutputStream("CreateExcelHiddenRow.xlsx");   
  wb.write(out);
  out.close();
  wb.close();

 }
}

答案 1 :(得分:0)

您可以创建新的行样式。相反,获取行&#39;现有样式并添加您的规则:

currentRow.getRowStyle().setHidden(true);

您可以参考this post

编辑:您甚至可以创建一个新的单元格样式作为@RC提及。