我制作了我的小專案(c# app)your text,它將資料從 sql 資料庫匯出到 csv 檔案中。我想從 | 更改日期格式 10.01.2022 至 -> 2022.01.10。
感謝幫助。
問候,
維生素
using System.Data;
using System.Data.SqlClient;
namespace ExtractApp
{
class Program
{
static void Main(string[] args)
{
GetCSV();
}
private static string GetCSV()
{
using (SqlConnection cn = new SqlConnection(GetConnectionString()))
{
cn.Open();
return CreateCSV(new SqlCommand("Select * from [reports].[xxx]", cn).ExecuteReader());
cn.Close();
}
}
private static string CreateCSV(IDataReader reader)
{
string file = "C:\\SqlToCsv\\Data.csv";
List<string> lines = new List<string>();
string headerLine = "";
if (reader.Read())
{
string[] columns = new string[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i )
{
columns[i] = reader.GetName(i);
}
headerLine = string.Join(",", columns);
lines.Add(headerLine);
}
//data
while (reader.Read())
{
object[] values = new object[reader.FieldCount];
reader.GetValues(values);
lines.Add(string.Join(",", values));
}
//file
System.IO.File.WriteAllLines(file, lines);
return file;
}
}
}
uj5u.com熱心網友回復:
由于您的列型別是Date,它將被映射到C# 中的DateTime( docs ),因此我們可以使用模式匹配來獲取并使用以下方法DateTime將其轉換為 a :string.ToString
object[] values = new object[reader.FieldCount];
reader.GetValues(values);
for (int i = 0; i < values.Length; i)
{
if (values[i] is DateTime dateTimeValue)
{
values[i] = dateTimeValue.ToString("yyyy.MM.dd", System.Globalization.CultureInfo.InvariantCulture);
}
}
lines.Add(string.Join(",", values));
更多資訊:
- 模式匹配
- 標準日期和時間格式字串
- 自定義日期和時間格式字串
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/453945.html
上一篇:如何從表中選擇不同值的最大日期
