[英]How can I get CSV file encoding UTF-8 in C#.Net?
我想制作UTF-8編碼的CSV文件。 現在,我的CSV文件無法顯示日文字體。 我想要C#代碼來解決這個問題。
SuSanda,
我不確定您當前的代碼或您嘗試保存的實際文本,但這可能會讓您朝着正確的方向前進。
using(var sw = new StreamWriter("testfile_utf8.csv", false, Encoding.UTF8))
{
sw.WriteLine("頼もう");
}
如果您在Excel中打開該文件,它將按預期顯示日語文本。
如果您不包含Encoding.UTF8
參數,它將顯示亂碼。
我希望這就是你要找的東西。
此代碼有助於從csv文件中將文本保存為編碼的csv文件。 使用方法如下呼叫並保存。
GetCSVFileContent( “Your_CSV_FileName”)
protected byte[] GetCSVFileContent(string fileName)
{
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(fileName, Encoding.Default, true))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
}
string allines = sb.ToString();
UTF8Encoding utf8 = new UTF8Encoding();
var preamble = utf8.GetPreamble();
var data = utf8.GetBytes(allines);
return data;
}
StringBuilder sb = new StringBuilder();
var columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
var fields = row.ItemArray.Select(field => field.ToString()).ToArray();
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText(fileName, sb.ToString(), Encoding.UTF8);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.