A supplier's CSV can look fine in a text editor and still lose product codes or split a single note across two worksheet rows. In Delphi, import it with HotXLS TXLSXWorkbook.OpenCSV, check the types and contents your report depends on, and use SaveAsHTML to publish the first worksheet as an HTML table.
What keeps a multiline field in one CSV row?
A CSV record ends at a line break outside quotes. Inside a quoted field, the break belongs to the cell, just like a comma or an escaped quote. A reader that splits the file into lines before interpreting the quotes sees a spurious row and can shift the following records. inventory.csv uses CRLF between records and inside one note. The supplier feed therefore has four logical rows including its header, whilst a text editor may show five lines of content. For the exact rules on commas, line breaks, and doubled quotes inside a field, read the quoted-field grammar in section 2 of RFC 4180, which says when a record ends and how a quote is escaped.
The byte-order mark (BOM) belongs to the encoding layer. The three bytes EF BB BF tell the loader that the input is UTF-8, and they are gone before the header is interpreted. HotXLS also recognises UTF-16 BOMs. Without a BOM, the loader accepts valid UTF-8. Anything else is decoded with the system code page, with Windows-1252 as the fallback when that setting is missing or is itself UTF-8. An explicit UTF-8 interchange agreement with the supplier avoids that guess, especially for a job that runs on machines with different regional settings. The guide to Unicode and spreadsheet export covers what to check at those file boundaries. Café mug is in the data for the decoding. PrintInventory, further down, prints that name, and a file saved in one code page but decoded with another shows up there as a mangled name. Its é comes from a Unicode character literal, so copying the example into a source file with a different editor encoding leaves the bytes unchanged. The procedures below are pieces of one console program, and the first block opens with the uses clause they all need. Each source line that ends with CRLF contributes those two bytes to the file. Call WriteSampleCsv('inventory.csv') in a writable working directory before anything else.
uses
Classes, SysUtils, Variants, lxHandleX;
procedure WriteSampleCsv(const FileName: string);
const
CRLF = #13#10;
Bom: array[0..2] of Byte = ($EF, $BB, $BF);
var
Data: UTF8String;
Output: TFileStream;
begin
Data := UTF8Encode(UnicodeString(
'Product,SKU,Qty,InStock,Added,Note' + CRLF +
'Caf' + #$00E9 + ' mug,00150,1500,True,2026-06-02,"Top, seller"' + CRLF +
'Tea cup,00320,320,False,2025-12-31,"first line' + CRLF +
'second ""quoted"" line"' + CRLF +
'"=SUM(A1)",00007,,True,2026-01-15,"Size < large & in stock"' + CRLF));
Output := TFileStream.Create(FileName, fmCreate);
try
Output.WriteBuffer(Bom[0], SizeOf(Bom));
Output.WriteBuffer(Data[1], Length(Data));
finally
Output.Free;
end;
end;
How do you preserve leading zeros in CSV import?
Pass False as the third argument to TXLSXWorkbook.OpenCSV when the exact spelling of a field carries meaning. In the SKU column of inventory.csv, 00150 and 150 can identify different stock items. Quotes do not keep the zeros. CSV quotes describe field boundaries, so a code wrapped in quotes is still eligible for type inference. The filename-only overload detects the separator and enables type inference. There the quantity 1500 becomes numeric, True becomes a Boolean, and 2026-06-02 becomes a date. The example pins the delimiter. This supplier's feed already has a known layout, so the separator is passed as an explicit comma.
For a display-only preview, keeping nonempty values as text preserves the identifiers and date spellings that the supplier sent. Calculations want typed columns. If the worksheet feeds a total or an inventory rule, convert the documented quantity, Boolean, or date columns after checking the headers, which gives each column its own rule. A blank quantity is not zero. It has its own meaning and deserves a different treatment from a recorded quantity of zero. A fresh workbook helps here. It keeps imported data away from existing sheets whilst you check the preview. A support ticket about wrong quantities is easier to investigate when the selected type policy was recorded with the output. A second import of those bytes into another fresh workbook, this time with OpenCSV(CsvName, ',', True), yields the typed column of the table below. It compares the stored values, not what Excel or a browser displays, for the first data row.
| Cell | Type detection off | Type detection on | What the report cares about |
|---|---|---|---|
| B2, SKU | Text 00150 | Number 150 | Exact identifier, including the leading zeros |
| C2, Qty | Text 1500 | Number 1500 | A number for a total, text for a faithful preview |
| D2, InStock | Text True | Boolean True | A Boolean for inventory logic |
| E2, Added | Text 2026-06-02 | Date displayed as 2026-06-02 | A date for calendar calculations |
Look at both Value and Formula when input resembles a calculation. With type detection off, OpenCSV stores =SUM(A1) as literal text. Value holds the full string and Formula is empty. A preview that compares only what appears on screen would miss a populated formula slot. PrintInventory writes the stored values to the console instead of raising on a mismatch. The output also covers a quote and a line break in F3, the empty field at C4, and the field to its right. Together they catch the common parsing mistakes where a missing value shifts the rest of a record left. The blank field goes through HasCell, because reading Cells[4, 3] would create a cell for that empty coordinate.
procedure PrintInventory(Sheet: TXLSXWorksheet);
begin
Writeln('A1: ', VarToStr(Sheet.Cells[1, 1].Value));
Writeln('A2: ', VarToStr(Sheet.Cells[2, 1].Value));
Writeln('B2: ', VarToStr(Sheet.Cells[2, 2].Value));
Writeln('F2: ', VarToStr(Sheet.Cells[2, 6].Value));
Writeln('F3: ', VarToStr(Sheet.Cells[3, 6].Value));
Writeln('C4 present: ', Sheet.Cells.HasCell(4, 3));
Writeln('D4: ', VarToStr(Sheet.Cells[4, 4].Value));
Writeln('A4 value: ', VarToStr(Sheet.Cells[4, 1].Value));
Writeln('A4 formula length: ', Length(Sheet.Cells[4, 1].Formula));
end;
Expected output:
A1: Product
A2: Café mug
B2: 00150
F2: Top, seller
F3: first line
second "quoted" line
C4 present: FALSE
D4: True
A4 value: =SUM(A1)
A4 formula length: 0
A semicolon-delimited CSV from a stream
A stream import takes a separator and a type policy, like a file import. For a buffered upload, TXLSXWorkbook.OpenCSV(Input, ';', False) reads from the stream's current position and keeps a stock code such as 00120 as text. The input is built in memory from two lines, the header Name;SKU;Active;Due and a record whose first field is the quoted "Widget; premium". After the import the code prints A2 and B2, writes the worksheet back with SaveAsCSV(Exported, 0, ';'), rewinds the exported stream, and loads it into a second workbook. It prints A2: Widget; premium, B2: 00120, and Reloaded B2: 00120. The quoted semicolon survives, and so do all five digits. Type detection changes that. With it enabled, that B2 text is eligible for conversion to the number 120. The round trip compares worksheet values across the two calls, so the CSV writer may quote a field either way as long as the value survives.
procedure CheckSemicolonRoundTrip;
const
CRLF = #13#10;
var
Book, Reloaded: TXLSXWorkbook;
Input, Exported: TMemoryStream;
Data: UTF8String;
begin
Data := UTF8Encode('Name;SKU;Active;Due' + CRLF +
'"Widget; premium";00120;true;2026-06-29' + CRLF);
Input := TMemoryStream.Create;
try
Input.WriteBuffer(Data[1], Length(Data));
Book := TXLSXWorkbook.Create;
try
Input.Position := 0;
if Book.OpenCSV(Input, ';', False) <> 1 then
raise Exception.Create('Could not read the CSV stream');
Writeln('A2: ', VarToStr(Book.Sheets[1].Cells[2, 1].Value));
Writeln('B2: ', VarToStr(Book.Sheets[1].Cells[2, 2].Value));
Exported := TMemoryStream.Create;
try
if Book.SaveAsCSV(Exported, 0, ';') <> 0 then
raise Exception.Create('Could not write the CSV stream');
Exported.Position := 0;
Reloaded := TXLSXWorkbook.Create;
try
if Reloaded.OpenCSV(Exported, ';', False) <> 1 then
raise Exception.Create('Could not read the CSV stream');
Writeln('Reloaded B2: ',
VarToStr(Reloaded.Sheets[1].Cells[2, 2].Value));
finally
Reloaded.Free;
end;
finally
Exported.Free;
end;
finally
Book.Free;
end;
finally
Input.Free;
end;
end;
An HTML fragment for an existing page
For an HTML table that goes inside an existing page, set WriteDocument, IncludeStyles, and IncludeBOM to False and give TableClass a name that the application owns. The output is UTF-8. The surrounding page supplies the document, its charset, and the CSS for .inventory-preview. A table cell can retain a newline in its text whilst showing the words on one line under normal browser whitespace rules, so style the note cells with white-space: pre-line if the break between the two lines should be visible. The worksheet's value and the browser's layout are two different checks. For a portal, scope the CSS to this table so a change in note wrapping leaves the page headers and forms alone. Two indexes appear in the code. Only one of them starts at one. Book.Sheets[1] is the first worksheet, because the Sheets indexer is one-based. The positional argument of SaveAsHTML counts from zero, so the call that exports that sheet uses 0. Each number sits beside its own call, which keeps the intent clear when an application gains extra tabs.
procedure PublishInventory(const CsvName, FragmentName, DocumentName: string);
var
Book: TXLSXWorkbook;
Options: TXLSXHtmlExportOptions;
HeaderFont: Integer;
begin
Book := TXLSXWorkbook.Create;
try
if Book.OpenCSV(CsvName, ',', False) <> 1 then
raise Exception.Create('Could not open the CSV file');
PrintInventory(Book.Sheets[1]);
HeaderFont := Book.Fonts.Add('Calibri', 11, True, False);
Book.Sheets[1].Range['A1:F1'].SetFontIndex(HeaderFont + 1);
Options := TXLSXHtmlExportOptions.Create;
try
Options.WriteDocument := False;
Options.IncludeStyles := False;
Options.IncludeBOM := False;
Options.TableClass := 'inventory-preview';
if Book.SaveAsHTML(FragmentName, 0, Options) <> 0 then
raise Exception.Create('Could not write the HTML fragment');
Options.Title := 'Supplier Inventory';
Options.WriteDocument := True;
Options.IncludeStyles := True;
Options.IncludeBOM := True;
if Book.SaveAsHTML(DocumentName, 0, Options) <> 0 then
raise Exception.Create('Could not write the HTML document');
finally
Options.Free;
end;
finally
Book.Free;
end;
end;
The code writes both forms from one data set. Title sets the document title when the exporter writes the full page, and that complete document can be opened directly in a browser for review. The fragment fits a portal template. Its header row styling is left to the page that embeds it. A bold workbook font is added so the two exports show an actual styling difference. Font indexes differ by one. The font collection returns a zero-based index, and the range setter takes a one-based one, hence HeaderFont + 1. Once WriteSampleCsv has produced inventory.csv, PublishInventory('inventory.csv', 'inventory-fragment.html', 'inventory.html') prints the values above and writes both files. The standalone document should show four rows, a bold first row, the accented product name, and the original stock codes. In the fragment source, the supplier's final note appears as Size < large & in stock. In the browser it reads Size < large & in stock. That difference is intentional. The HTML exporter escapes worksheet cell text at the point where it writes markup. Pre-escaping the CSV fields would put sequences such as < into the workbook data itself.
The same import policy in C++Builder and Excel output
C++Builder exposes the filename, separator, and type-detection overload through lxHandleX.hpp. Its snippet mirrors the calls above with the generated headers: an options object and the zero-based positional argument select the first worksheet for HTML export. In a production port, print Value and Formula for the cells that PrintInventory covers before writing the fragment. To reach the first worksheet, use book->Sheets->Items[1]. Its Cells->Item[row][col] entries take one-based row and column coordinates, matching the Pascal examples.
#include <System.SysUtils.hpp>
#include <memory>
#include "lxHandleX.hpp"
void WriteInventoryFragment()
{
std::unique_ptr<TXLSXWorkbook> book(new TXLSXWorkbook());
if (book->OpenCSV(System::WideString(L"inventory.csv"), L',', false) != 1)
throw System::Sysutils::Exception(L"Could not open the CSV file");
std::unique_ptr<TXLSXHtmlExportOptions> options(
new TXLSXHtmlExportOptions());
options->WriteDocument = false;
options->IncludeStyles = false;
options->IncludeBOM = false;
options->TableClass = L"inventory-preview";
if (book->SaveAsHTML(System::WideString(L"inventory-fragment.html"), 0,
options.get()) != 0)
throw System::Sysutils::Exception(L"Could not write the HTML fragment");
}
For a downloadable workbook, save the imported TXLSXWorkbook with SaveAs. SaveImportedWorkbook('inventory.csv', 'inventory.xlsx') reuses the separator and the type policy of the HTML export. The file extension picks the format. A name ending in .xlsx writes an Open XML package. These calls do not share one success value. OpenCSV returns 1 when it parsed at least one record and 0 for an empty input, and a file that cannot be opened gives -1. SaveAsCSV and SaveAsHTML return 0 on success and -1 when the sheet index is out of range. SaveAs returns 1. Every guard in this article compares the result with that one value. A legacy recipient can use TXLSWorkbook.OpenCSV from lxHandle on the supplier CSV and save an .xls file. The workbook gets its own output name. That lets you open it in Excel and compare its SKU column with the source. If the recipient expects another CSV, check what the receiving spreadsheet does with identifiers and formula-like strings when it opens the file. Quoting protects the field boundaries. The recipient's import policy decides the resulting cell types. The overview of CSV, TSV, HTML, and RTF export goes into the format choices and the stream overloads.
procedure SaveImportedWorkbook(const CsvName, OutputFile: string);
var
Book: TXLSXWorkbook;
begin
Book := TXLSXWorkbook.Create;
try
if Book.OpenCSV(CsvName, ',', False) <> 1 then
raise Exception.Create('Could not open the CSV file');
if Book.SaveAs(OutputFile) <> 1 then
raise Exception.Create('Could not write the workbook');
finally
Book.Free;
end;
end;
Keep the supplier file. It stays the input for future imports, even when the team exchanges the HTML preview more often. That gives support a way to retrace a surprising row back to its delimiters and encoding, and it gives the publishing job a way to regenerate the preview after a change to the page design. Teams that also deliver editable reports can reuse the printed Value and Formula checks before saving Excel files with the HotXLS spreadsheet component for Delphi and C++Builder.