2013-09-26 61 views
0

我正在使用C#中的OLEDBConnection讀取Excel文件。如何更改讀取Excel的c#應用程序的日期格式文化

我想根據Excel文件的文化更改當前的線程文化,所以我可以在文化特定的格式中獲取日期。我使用了下面的代碼,但它不工作。它仍然將日期轉換爲我們的英文格式。如果我從Control Panel --> Region and Language改變格式,那麼它的工作原理:

See screen shot

我的代碼:

public static System.Data.DataTable GetWorksheet(string worksheetName, string connectionString) 
{ 
    try 
    { 
     Thread.CurrentThread.CurrentCulture = new CultureInfo("cs-CZ", true); 
     Thread.CurrentThread.CurrentCulture.ClearCachedData(); 
     OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString); 
     OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter(
     //"select * from [" + worksheetName + "]", con); 
     "select * from [" + worksheetName + "$]", con); 

     con.Open(); 
     System.Data.DataSet excelDataSet = new DataSet(); 
     cmd.Fill(excelDataSet); 
     con.Close(); 
     con.Dispose(); 
     System.Data.DataTable dt = excelDataSet.Tables[0]; 
     if (excelDataSet != null) 
     excelDataSet.Dispose(); 

     return dt; 
    } 
    catch (Exception e) 
    { 
     throw e; 
    } 
} 
+0

'Thread.CurrentThread.CurrentCulture.ClearCachedData();'看起來很可疑。嘗試發表評論 –

+0

看起來像你的問題是'Thread.CurrentThread.CurrentCulture = new CultureInfo(「cs-CZ」,true);' 使用重載'Thread.CurrentThread.CurrentCulture = new CultureInfo(「cs-CZ」) ;'因爲布爾表明你應該在你的機器上使用用戶設置的文化......我相信 –

回答

0

從微軟退房的例子here。他們使用:

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR"); 
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("fr-FR"); 
+0

「CurrentUICulture」是資源管理器,在這種情況下不需要 –