Skip to content

Commit b51b1ac

Browse files
author
Ravi Mohan
committed
1. Allow tab to be used as CSVDelimiter
2. Option to include Excel Delimiter Header, allowing the downloaded file to be opened in excel directly.
1 parent 57f01ee commit b51b1ac

File tree

4 files changed

+12
-2
lines changed

4 files changed

+12
-2
lines changed

src/WebApiContrib.Core.Formatter.Csv/CsvFormatterMvcBuilderExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public static IMvcBuilder AddCsvSerializerFormatters( this IMvcBuilder builder,
3030
csvFormatterOptions = new CsvFormatterOptions();
3131
}
3232

33-
if (string.IsNullOrWhiteSpace(csvFormatterOptions.CsvDelimiter))
33+
if (string.IsNullOrEmpty(csvFormatterOptions.CsvDelimiter))
3434
{
3535
throw new ArgumentException("CsvDelimiter cannot be empty");
3636
}

src/WebApiContrib.Core.Formatter.Csv/CsvFormatterOptions.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,7 @@ public class CsvFormatterOptions
77
public string CsvDelimiter { get; set; } = ";";
88

99
public string Encoding { get; set; } = "ISO-8859-1";
10+
11+
public bool IncludeExcelDelimiterHeader { get; set; } = false;
1012
}
1113
}

src/WebApiContrib.Core.Formatter.Csv/CsvOutputFormatter.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,11 @@ public async override Task WriteResponseBodyAsync(OutputFormatterWriteContext co
8787

8888
var streamWriter = new StreamWriter(response.Body, Encoding.GetEncoding(_options.Encoding));
8989

90+
if (_options.IncludeExcelDelimiterHeader)
91+
{
92+
await streamWriter.WriteLineAsync($"sep ={_options.CsvDelimiter}");
93+
}
94+
9095
if (_options.UseSingleLineHeaderInCsv)
9196
{
9297
var values = useJsonAttributes

src/WebApiContrib.Core.Formatter.Csv/README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,13 +124,16 @@ The formatters can be added to the ASP.NET Core project in the Startup class in
124124

125125
The default delimiter is set to ';' and the header is included by default.
126126

127+
Optionally setting IncludeExcelDelimiterHeader to true adds the "sep=," header, so the files can be opened in Excel directly.
128+
127129
```csharp
128130
public void ConfigureServices(IServiceCollection services)
129131
{
130132
//var csvOptions = new CsvFormatterOptions
131133
//{
132134
// UseSingleLineHeaderInCsv = true,
133-
// CsvDelimiter = ","
135+
// CsvDelimiter = ",",
136+
// IncludeExcelDelimiterHeader = true
134137
//};
135138
136139
//services.AddMvc()

0 commit comments

Comments
 (0)