我正在嘗試下載 CSV 檔案并決議其欄位,并且我正在使用 CSVHelper 庫(https://joshclose.github.io/CsvHelper)。我認為我面臨的問題與編碼有關,因為當我在代碼中讀取/列印檔案內容時,CsvHelper 庫找不到相關的標頭/欄位。我以 word 格式匯入檔案,UTF8 似乎是正確的編碼,以便正確顯示 CSV 內容。但是,我的代碼和 excel 無法正確顯示標題(或任何捷克字符)。這是我如何獲得excel:
var teamResultCsvUrl = new Uri("https://blabla/csv/4072");
這是我想做的事情:
// total results for teams
using (response = await client.GetAsync(teamResultCsvUrl))
{
using (Stream stream = await response.Content.ReadAsStreamAsync())
{
using (StreamReader streamReader = new StreamReader(stream))
using (CsvHelper.CsvReader csvReader = new CsvHelper.CsvReader(streamReader, CultureInfo.InvariantCulture))
{
teamCsvResults = csvReader.GetRecords<ValidationClass>().ToList();
}
}
}
我收到以下例外:
System.AggregateException: One or more errors occurred.
CsvHelper.HeaderValidationException: Header with name '<SOME HEADER>' was not found. If you are expecting some headers to be missing and want to ignore this validation, set the configuration HeaderValidated to null. You can also change the functionality to do something else, like logging the issue.
at CsvHelper.Configuration.ConfigurationFunctions.HeaderValidated(Boolean isValid, String[] headerNames, Int32 headerNameIndex, ReadingContext context)
at CsvHelper.CsvReader.ValidateHeader(ClassMap map)
at CsvHelper.CsvReader.ValidateHeader(Type type)
at CsvHelper.CsvReader.ValidateHeader[T]()
at CsvHelper.CsvReader.<GetRecords>d__63`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
.......
此外,當我列印檔案內容時,字符編碼不正確。如何/在哪里可以設定下載檔案的編碼?我的方法還有什么看起來不對的地方嗎?
謝謝!
uj5u.com熱心網友回復:
CsvHelper
不控制用于讀取資料的編碼。您可以在創建StreamReader
.
using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
如果Encoding.UTF8
不起作用,您可能需要弄清楚正確的編碼是什么。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/450977.html
上一篇:FileNotFoundException:無法在IIS上加載檔案或程式集'Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer,Version=5
下一篇:從自定義int計算百分比