Quick revision
The short answer
We open an XSSFWorkbook and an output stream in try-with-resources, create a sheet, write a bold header row and one row per order, and give the Amount cells a single shared CellStyle with a currency data format. Amounts are written as numbers with setCellValue(double), so Excel can sum them. After all rows are written we call autoSizeColumn for each column and then wb.write(out).
What to remember
In this answer, we built an .xlsx export with Apache POI: an XSSFWorkbook and output stream in try-with-resources, a bold header row, one row per order, amounts written as doubles with one shared currency style, and columns auto-sized after the data. We saw why styles must be created once (the workbook's style table has a limit of about 64,000), why numbers must be numeric cells and BigDecimal must be rounded before conversion, why autoSizeColumn is slow on large sheets, and that HSSF is for old .xls files limited to 65,536 rows while XSSF handles .xlsx.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We open an XSSFWorkbook and an output stream in try-with-resources, create a sheet, write a bold header row and one row per order, and give the Amount cells a single shared CellStyle with a currency data format. Amounts are written as numbers with setCellValue(double), so Excel can sum them. After all rows are written we call autoSizeColumn for each column and then wb.write(out).
Why this question is asked
Almost every business application ends up exporting something to Excel: orders, invoices, payroll lines. Apache POI is the standard Java library for it, and the small details of a POI export decide whether finance can use the file: numbers that are real numbers, a currency format, readable column widths. Interviewers use this task to see whether we know those details and the traps behind them, such as the cell style limit. In this answer, we will recap POI's object model, write the export step by step, look at the style limit and BigDecimal conversion, and finish with column sizing and the difference between HSSF and XSSF.
1A Quick Recap of POI's Object Model
POI mirrors the structure of a spreadsheet. A Workbook is the whole file, a Sheet is one tab, a Row is one line of a sheet and a Cell is one box in a row. Rows and cells are numbered from zero, so Excel's row 1 is POI row 0 and column C is cell index 2.
POI has several implementations of these interfaces. XSSFWorkbook writes the modern .xlsx format, which is a ZIP file of XML documents. HSSFWorkbook writes the old binary .xls format. SXSSFWorkbook is a streaming version of XSSF for very large files. Because they share the Workbook, Sheet, Row and Cell interfaces, most of our code does not depend on which one we pick.
Formatting lives in a CellStyle, which holds the font, borders, alignment and the data format. A data format is the same kind of format code we type in Excel's Format Cells dialog, such as #,##0.00, and it changes only how a number is displayed, not the number itself.
2Writing the Workbook Step by Step
Here is the full export. We create the styles once, before the loop, and then write the header and the data rows.
- Create workbook and output streamtry-with-resources
- Create styles onceheader font, money format
- Write header rowrow 0
- Write one row per ordernumbers as double, shared style
- Freeze header, auto-size columnsafter all data
- wb.write(out)then both resources close
6 steps in order. Play them, or step through them one at a time.
Notice the order in try-with-resources. Resources close in reverse order, so the stream closes first and then the workbook, and both happen after wb.write(out) has finished. If anything throws while we build the sheet, both are still closed and no half-open file handle leaks.
Notice also that the format code puts the dollar sign in quotes. That makes it a literal symbol. For a format that follows the reader's locale or a specific currency, Excel uses codes such as [$EUR] inside the format, and the right code depends on what finance expects, so it is worth agreeing on it with them.
3Why We Create the Style Only Once
A common mistake is to create a new CellStyle inside the loop, one per amount cell. It looks harmless, because each style is identical. But a workbook stores styles in a shared table, and every createCellStyle() call adds an entry to it. An .xlsx file can hold about 64,000 styles and an .xls file about 4,000. With 70,000 orders, the export fails part way through.
Even below the limit, thousands of duplicate styles make the file bigger and slower to open. So we treat styles like constants: create each distinct style once, keep it in a variable or a small map, and reuse it for every cell that needs it.
4Writing Numbers So Excel Can Sum Them
If we wrote the amount with setCellValue(o.amount().toString()), the cell would contain the text "1234.50". It would look right, but Excel would show the little green warning triangle, SUM would ignore it, and sorting would be alphabetical. The cell must be numeric, which means setCellValue(double).
Our amounts are BigDecimal, which is exact, while Excel stores every number as a double with about 15 significant digits. For normal money values this is fine, but we convert deliberately: setScale(2, RoundingMode.HALF_UP) first, so the value Excel stores is the rounded amount we mean, and doubleValue() only then. Amounts with more than 15 significant digits would lose precision in Excel itself, so very large or very precise values should be exported as text with a note, or kept out of spreadsheets.
5Auto-Sizing Columns and Choosing HSSF or XSSF
autoSizeColumn(i) measures the text of every cell in the column and sets the width to fit the widest. We call it once per column, after all data is written; calling it before the rows exist measures nothing. It uses Java's font metrics to measure text, so on a Linux server we run with java.awt.headless=true and need the fonts installed, or the widths may be wrong. It is also slow, because it reads every cell: fine for a few thousand rows, painful for hundreds of thousands. For large sheets we set fixed widths with sheet.setColumnWidth(i, 20 * 256), where the unit is 1/256 of a character width.
Finally, the choice of format. HSSF writes .xls, the format used up to Excel 2003, limited to 65,536 rows and 256 columns per sheet. XSSF writes .xlsx, with 1,048,576 rows and 16,384 columns. Unless a consumer can only read .xls, we use XSSF, and for very large exports its streaming relative SXSSF.
6Follow-up questions
How would you add a total row at the bottom?
We add one more row after the data and put a formula in the amount column: cell.setCellFormula("SUM(C2:C" + r + ")") with the same money style. Excel calculates it when the file opens. If the total must also be correct for programs that read the file without calculating, we can call wb.getCreationHelper().createFormulaEvaluator().evaluateAll() before writing, which stores the result in the file.
Why not just write a CSV instead?
A CSV has no types, styles or formats, so Excel guesses: it may strip leading zeros from ids, change dates and ignore the currency format. CSV is the right choice for data exchange between systems and very large data; .xlsx is better when a person will open the file and expects numbers, formats and column widths to be right.
Is XSSFWorkbook thread-safe?
No. A workbook and its sheets should be built by one thread. If we generate several exports at once, each request creates its own workbook, which is the natural way to write it anyway.
7Conclusion
In this answer, we built an .xlsx export with Apache POI: an XSSFWorkbook and output stream in try-with-resources, a bold header row, one row per order, amounts written as doubles with one shared currency style, and columns auto-sized after the data. We saw why styles must be created once (the workbook's style table has a limit of about 64,000), why numbers must be numeric cells and BigDecimal must be rounded before conversion, why autoSizeColumn is slow on large sheets, and that HSSF is for old .xls files limited to 65,536 rows while XSSF handles .xlsx.
Open with
I would open an XSSFWorkbook and the output stream together in try-with-resources so both are closed even if something fails, then create a sheet called Orders. Before the loop I create the styles once: a bold font for the header and a money style whose data format comes from wb.createDataFormat().getFormat, for example a dollar sign with #,##0.00.
Then, if they want more
Creating a style per cell is a classic bug, because the workbook has a style table limited to about 64,000 entries in .xlsx and 4,000 in .xls.
I write the header in row zero, then one row per order: the id and customer as strings, and the amount with setCellValue of a double, so Excel treats it as a number it can sum and sort. Because the amount is a BigDecimal, I set the scale to two with HALF_UP before calling doubleValue.
After all the rows I freeze the header, call autoSizeColumn for each column, which is fine here but slow on large sheets where I would use fixed widths, and finally wb.write(out). I would use XSSF for .xlsx; HSSF is only for legacy .xls with its 65,536-row limit.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Use Apache POI to create an .xlsx file with a header row (Order, Customer, Amount) and...": https://scrivio-interview-library.netlify.app/java/document-libraries/d701685a37/