我正在 .net 8 中使用 Blazor 服务器。我正在尝试保存 CSV 文件,并使用 jitbit/CsvExport 来执行此操作。问题是附加字符被添加到第一个条目中。
我的 razor.cs 文件如下所示:
private async Task ExportToCSV()
{
var myExport = new CsvExport(includeColumnSeparatorDefinitionPreamble: false, includeHeaderRow: false);
myExport.AddRow();
myExport["Directions"] = "Directions";
myExport["Leg"] = "Leg";
myExport["LegTime"] = "Leg Time";
myExport["Trip"] = "Trip";
myExport["TripTime"] = "Trip Time";
foreach (var direction in LoadedDrivingDirections)
{
var row = new object[5]
{
$"{direction.Maneuver} on {direction.Road}",
direction.LegDistance.ToString("0.00"),
TimeSpan.FromMinutes(direction.Time).ToString(@"hh\:mm"),
direction.DistanceAtStart.ToString("0.00"),
TimeSpan.FromMinutes(drivingDirectionViews.Where(w => w.Direction.Latitude == direction.Latitude).Select(s => s.TotalTime).FirstOrDefault()).ToString(@"hh\:mm")
};
myExport.AddRow();
myExport["Directions"] = row[0];
myExport["Leg"] = row[1];
myExport["LegTime"] = row[2];
myExport["Trip"] = row[3];
myExport["TripTime"] = row[4];
}
await _js.SaveAs("ProMilesTrip.csv", myExport.ExportAsMemoryStream().ToArray());
}
我的js函数如下:
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob) {
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
CSV 开头的字符似乎是字节顺序标记。
由于您使用的是jitbit/CsvExport,因此方法
CsvExport.ExportAsMemoryStream(Encoding encoding = null)
有一个可选参数Encoding encoding
:
private readonly Encoding _defaultEncoding = Encoding.UTF8; public MemoryStream ExportAsMemoryStream(Encoding encoding = null) { MemoryStream ms = new MemoryStream(); encoding = encoding ?? _defaultEncoding;
Encoding.UTF8
:
对象,该对象提供 Unicode 字节顺序标记 (BOM)。UTF8Encoding
既然你不想这样,你应该传入你自己的
UTF8Encoding
,并将构造函数参数encoderShouldEmitUTF8Identifier
设置为false
:
_js.SaveAs("ProMilesTrip.csv",
myExport.ExportAsMemoryStream(encoding : new UTF8Encoding(false)).ToArray());