CSV export
On this page
Verify commas, quotes and newlines
Install TExcel from quick start, put this program in Program.cs and run dotnet run to view CSV containing a comma, double quotes and a newline:
using TExcel;
Excel.SaveAsCsv("notes.csv", new[]
{
new ExportRow { Code = "P-001", Note = "Pump, \"A\"\nSecond line" }
});
Console.Write(File.ReadAllText("notes.csv"));
/// <summary>固定 CSV 的列名和输出顺序。</summary>
public sealed class ExportRow
{
/// <summary>作为第一列输出的业务编码。</summary>
[ExcelColumn("Code", Order = 0)]
public string Code { get; set; } = "";
/// <summary>可能包含分隔符与多行内容的备注。</summary>
[ExcelColumn("Note", Order = 1)]
public string Note { get; set; } = "";
}Expected text:
Code,Note
P-001,"Pump, ""A""
Second line"The writer quotes fields containing commas, double quotes or newlines and doubles quotes inside them. Pass original values to the writer.
SaveAsCsv accepts entities, row dictionaries and column dictionaries, and has asynchronous save APIs. An existing file at the same path is recreated.
Append batches
using TExcel;
using var writer = Excel.CreateCsvWriter("devices.csv");
writer.WriteSheet(new[] { new { Code = "P-001", Name = "Inlet pump" } });
writer.AppendSheet(new[] { new { Code = "P-002", Name = "Outlet pump" } });
writer.Complete();AppendSheet adds data to the current output without repeating the header. It is not an option for opening an old file in append mode. CSV allows one WriteSheet call to start its single table; use AppendSheet for later batches.
Choose CSV or XLSX
| Requirement | CSV | XLSX |
|---|---|---|
| Exchange one table with another system | UTF-8 text; agree on columns and types | Workbook format; the recipient needs an XLSX reader |
| Multiple sheets, widths, freeze panes or colors | Unsupported | Use the XLSX writer and styling APIs |
Preserve 000123 or long integers | Text preserves characters, but spreadsheet software may infer types | Define a text-column policy; see mapping |
| Supply rows in batches | WriteSheet, followed by AppendSheet | Append to the current worksheet; see streaming writes |
Encoding and stream ownership
CsvWriter uses UTF-8 and defaults to emitBom: true. Construct it directly when your receiving system requires explicit BOM control:
using TExcel;
using var output = new MemoryStream();
using (var writer = new CsvWriter(output, leaveOpen: true, emitBom: false))
{
writer.WriteSheet(new[] { new { Code = "P-001" } });
writer.Complete();
}
output.Position = 0;CreateCsvWriter uses the default BOM setting. With leaveOpen: true, the caller owns stream disposal. Completion does not rewind the stream.
Export contract
CSV escaping does not disable formula interpretation by receiving software. Handle untrusted text through the application’s export policy.