我是c#的新手,我正在尝试将表数据从sqlite 3数据库导出到csv但是日期时间格式在csv中已经改变,sqlite 3中的格式是:
2013-04-16 21:33:42.000
而csv中的日期时间显示为:
16/04/2013 21:33:42,
这是我的代码:
SQLiteConnection m_dbConnection;
//m_dbConnection = new SQLiteConnection("Data Source= C:/Users/IT-Administrator/Desktop/WebMobility.db; Version=3;");
m_dbConnection = new SQLiteConnection("Data source = F:/Explor/final test/WebMobility.db; Version=3;");
m_dbConnection.Open();
SQLiteCommand myCommand = new SQLiteCommand();
myCommand.Connection = m_dbConnection;
myCommand.CommandText = "select CompanyId,`DateTime`,Serial,ShortDeviceId,MatricolaA,Upper(Targa),CommonRoadDescription,RoadCivicNumber,GpsAddress,VerbaliVehicleTypeDescription,VehicleBrandDescription,VehicleModelDescription,CommonColorVehicleDescription,VerbaliRuleOneCode,VerbaliRuleOneDescription,VerbaliClosedNoteDescription,VerbaliRuleOnePoints,VerbaliMissedNotificationDescription from VerbaliData";
//myCommand.Connection = myConn;
DataTable data = new DataTable();
SQLiteDataAdapter myAdapter = new SQLiteDataAdapter(myCommand);
//myAdapter.SelectCommand = myCommand;
myAdapter.Fill(data);
dataGridView1.DataSource = data;
this.dataGridView1.Refresh();
if (dataGridView1.RowCount > 0)
{
string value = "";
DataGridViewRow dr = new DataGridViewRow();
StreamWriter swOut = new StreamWriter("F:/Explor/final test/finaltest12.csv");
//write header rows to csv
for (int i = 0; i <= dataGridView1.Columns.Count - 1; i++)
{
if (i > 0)
{
swOut.Write(",");
}
swOut.Write(dataGridView1.Columns[i].HeaderText);
}
swOut.WriteLine();
//write DataGridView rows to csv
for (int j = 0; j <= dataGridView1.Rows.Count - 1; j++)
{
if (j > 0)
{
swOut.WriteLine();
}
dr = dataGridView1.Rows[j];
for (int i = 0; i <= dataGridView1.Columns.Count - 1; i++)
{
if (i > 0)
{
swOut.Write(",");
}
value = dr.Cells[i].Value.ToString();
//replace comma's with spaces
value = value.Replace(',', ' ');
//replace embedded newlines with spaces
value = value.Replace(Environment.NewLine, " ");
swOut.Write(value);
}
}
swOut.Close();
}
m_dbConnection.Close();
答案 0 :(得分:2)
DateTime列没有格式。它只是用于显示以特定格式格式化列值的列内容的工具 说很明显你需要做同样的事情来在CSV文件上打印你的值。
在内部循环中,检查列是否为日期时间,然后将其值格式化为您的喜欢。
for (int i = 0; i <= dataGridView1.Columns.Count - 1; i++)
{
if (i > 0)
{
swOut.Write(",");
}
// Datetime column content transformed in a formatted string....
if(i == 1)
value = Convert.ToDateTime(dr.Cells[i].Value).ToString("yyyy-MM-dd hh:mm:ss.fff");
else
....
编辑如果你的单元格中有空值或空值,那么你需要在尝试转换之前检查它
// Datetime column content transformed in a formatted string....
if(i == 1)
{
object cellValue = dr.Cells[i].Value;
value = (cellValue == DBNull.Value ?
string.Empty : Convert.ToDateTime(cellValue).ToString("yyyy-MM-dd hh:mm:ss.fff");
}
这将写一个空列,其中包含日期。这可能是正确与否,具体取决于CSV文件的使用方式。您可以保存预定义值,而不是空字符串。
答案 1 :(得分:0)
if (i==1)
{
value = dr.Cells[i].Value.ToString();
if (value!null)
{
string dt=DateTime.Parse(value).ToString("yyyy/MM/dd hh:mm:ss");
swOut.Write(dt);
}
......
}