Excel Sheet Header

In this section, you will learn how to create header on a sheet using Apache POI.

Excel Sheet Header

Excel  Sheet Header

In this section, you will learn how to create header on a sheet using Apache POI.

In the given below example, we will create headers having different position on sheet.These headers will appear on the hardcopy(print out) . You can see this by taking print preview of the sheet.

Given below the code :

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

import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.CreationHelper;

public class XLHeader {
public static void main(String args[]) throws IOException {
Workbook wb = new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");

Row row = sheet.createRow((short) 0);
// Create a cell and put a value in it.
row.createCell(0).setCellValue(
createHelper.createRichTextString("Take Print Preview to View Headers"));
Header header = sheet.getHeader();
header.setCenter("Center Header");
header.setLeft("Left Header");
header.setRight(HSSFHeader.font("Stencil-Normal", "Italic")
+ HSSFHeader.fontSize((short) 10) + "Right Header");

FileOutputStream fileOut = new FileOutputStream(
"xls/workbookHeader.xls");
wb.write(fileOut);
fileOut.close();
}
}

OUTPUT

When you take its print preview, headers will appear like below :

Download Source Code