C# 为什么在.CSV文件中打开时日期显示不同

C# 为什么在.CSV文件中打开时日期显示不同,c#,regex,C#,Regex,我从一个文本文件中获取了数百行数据,该文本文件是使用Regex MatchCollection捕获的,并将其输出到一个逗号demlimited(csv)文件,以便在excel中进行后续检查 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; //for StreamReader and

我从一个文本文件中获取了数百行数据,该文本文件是使用Regex MatchCollection捕获的,并将其输出到一个逗号demlimited(csv)文件,以便在excel中进行后续检查

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; //for StreamReader and StreamWriter
using System.Text.RegularExpressions;
using System.Windows.Forms; 
using System.Globalization; //from two digit date to four digit date conversion.

namespace Experiment2
{
    class DemandRefundOnly
    {
      public line1 {get; set;}
      public Line3 {get; set;}
      DateTime dateTime;
      int FourDigitYear; 
      int Month; 
      int Day;
      DateTime dateTime;
      Regex Line3 = new Regex(@"(?<one>[0-9]{2}-[0-9]{2}-[0-9]{2})\s{1,20}114B\s{1,15}(?<two>\d{1,11})\s{1,15}(?<three>\d{1,11})\s{1,15}(?<four>\d{1,11})\s{1,30}(?<five>\d{1,11})");//Regex to capture data. //<one> catpures the date data.

      //Only the relevant date part is going to be shown in the output given.

      using (StreamReader Reader1 = new StreamReader(@"C:\Users\UK\data.txt"))
      { //StreamREader to read the input text file.
         using(StreamWriter Writer1 = new StreamWriter(@"C:\Users\Sample.csv"))
         { //StreamWriter to wrie to the output file.
            while((line1 = Reader1.ReadLine())!= null)
            { //to loop through the input file.
               MatchCollection matches = Line3.Matches(line1);
               foreach (Match m in matches)
               { //for...each to loop through and print the matches.
                  //Writer1.Write(m.Groups["one"].Value + ","); //this line modified with the following.


                 Day = Convert.ToInt32(m.Groups["one"].Value.Substring(0, 2));
                    //the above captures the first two digits date string contained in m.Groups["one"].Value and stores the first two characters as int to Day.
                 Month = Convert.ToInt32(m.Groups["one"].Value.Substring(3, 2));
                 FourDigitYear = Convert.ToInt32(m.Groups["one"].Value.Substring(6, 2));
                 FourDigitYear = CultureInfo.CurrentCulture.Calendar.ToFourDigitYear(FourDigitYear);
                 dateTime = new DateTime(FourDigitYear, Month, Day);
                 Writer1.WriteLine(dateTime);
               }
            }
         }
      }
   }
}
我的正则表达式如下所示:-

Regex Line3 = new Regex(@"(?<one>[0-9]{2}-[0-9]{2}-[0-9]{2})\s{1,20}114B\s{1,15}(?<two>\d{1,11})\s{1,15}(?<three>\d{1,11})\s{1,15}(?<four>\d{1,11})\s{1,30}(?<five>\d{1,11})");//<one> catpures the date data.

MatchCollection matches = Line3.Matches(line1);
foreach (Match m in matches)
{
    Writer1.WriteLine("")//
    //Writer1.Write(line1.Substring(1, 27) + ","); //Do not consider this.
    Writer1.Write(m.Groups["one"].Value + ",");
    Writer1.Write(m.Groups["two"].Value + ",");
    Writer1.Write(m.Groups["three"].Value + ",");
    Writer1.Write(m.Groups["four"].Value + ",");
    Writer1.Write(m.Groups["five"].Value + ",");
 }
我的输入文件看起来像

12-04-12                  114B           0             0              0                0
12-04-12                  114B           0             0              0                0
12-04-12                  114B           0             0              0                0
12-04-12                  114B           0             0              0                0
12-04-12                  114B           0             0              0                0
12-04-12                  114B           0             0              0                0
12-04-12                  114B        5467        757488         846815                0
13-04-12                  114B           0             0              0                0
13-04-12                  114B           0             0              0                0
20-04-12                  114B           0             0            500                0
21-04-12                  114B        1740         17905          17900                0
21-04-12                  114B           0             0              0                0
24-04-12                  114B        1466         31666          31420                0
当我用记事本检查.csv文件时,输出非常一致。只有在excel中打开csv文件时,问题才会出现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; //for StreamReader and StreamWriter
using System.Text.RegularExpressions;
using System.Windows.Forms; 
using System.Globalization; //from two digit date to four digit date conversion.

namespace Experiment2
{
    class DemandRefundOnly
    {
      public line1 {get; set;}
      public Line3 {get; set;}
      DateTime dateTime;
      int FourDigitYear; 
      int Month; 
      int Day;
      DateTime dateTime;
      Regex Line3 = new Regex(@"(?<one>[0-9]{2}-[0-9]{2}-[0-9]{2})\s{1,20}114B\s{1,15}(?<two>\d{1,11})\s{1,15}(?<three>\d{1,11})\s{1,15}(?<four>\d{1,11})\s{1,30}(?<five>\d{1,11})");//Regex to capture data. //<one> catpures the date data.

      //Only the relevant date part is going to be shown in the output given.

      using (StreamReader Reader1 = new StreamReader(@"C:\Users\UK\data.txt"))
      { //StreamREader to read the input text file.
         using(StreamWriter Writer1 = new StreamWriter(@"C:\Users\Sample.csv"))
         { //StreamWriter to wrie to the output file.
            while((line1 = Reader1.ReadLine())!= null)
            { //to loop through the input file.
               MatchCollection matches = Line3.Matches(line1);
               foreach (Match m in matches)
               { //for...each to loop through and print the matches.
                  //Writer1.Write(m.Groups["one"].Value + ","); //this line modified with the following.


                 Day = Convert.ToInt32(m.Groups["one"].Value.Substring(0, 2));
                    //the above captures the first two digits date string contained in m.Groups["one"].Value and stores the first two characters as int to Day.
                 Month = Convert.ToInt32(m.Groups["one"].Value.Substring(3, 2));
                 FourDigitYear = Convert.ToInt32(m.Groups["one"].Value.Substring(6, 2));
                 FourDigitYear = CultureInfo.CurrentCulture.Calendar.ToFourDigitYear(FourDigitYear);
                 dateTime = new DateTime(FourDigitYear, Month, Day);
                 Writer1.WriteLine(dateTime);
               }
            }
         }
      }
   }
}

有谁能帮助解决不一致的原因吗?

如果以yyyy-MM-dd格式输出日期,则Excel应将其解析为日期

您可以使用适当的CultureInfo将文本dd-MM-yy转换为日期时间,这样就可以轻松地以yyy-MM-dd格式写出日期

using System;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            string inFile = @"C:\temp\sampledata.txt";
            string outFile = @"C:\temp\sampledata.csv";

            //<one> catpures the date data:
            Regex re = new Regex(@"(?<one>[0-9]{2}-[0-9]{2}-[0-9]{2})\s{1,20}114B\s{1,15}(?<two>\d{1,11})\s{1,15}(?<three>\d{1,11})\s{1,15}(?<four>\d{1,11})\s{1,30}(?<five>\d{1,11})");

            using (var sr = new StreamReader(inFile))
            {
                using (var sw = new StreamWriter(outFile))
                {
                    string line1;
                    DateTime dt;
                    var ci = new CultureInfo("ur-PK");
                    while (!sr.EndOfStream)
                    {
                        line1 = sr.ReadLine();
                        MatchCollection matches = re.Matches(line1);
                        foreach (Match m in matches)
                        {
                            dt = DateTime.Parse(m.Groups["one"].Value, ci);
                            sw.Write(dt.ToString("yyyy-MM-dd") + ",");
                            sw.Write(m.Groups["two"].Value + ",");
                            sw.Write(m.Groups["three"].Value + ",");
                            sw.Write(m.Groups["four"].Value + ",");
                            sw.Write(m.Groups["five"].Value + Environment.NewLine);
                        }
                    }
                }
            }
        }
    }
}
在Excel中打开csv文件时,无论Windows日期格式设置如何,它都应将“2012-04-12”等识别为日期。我没有Excel可供测试


然后,它应该在Windows短日期格式设置中显示日期。

为了解决问题,我考虑了我的其他人尤其是安德鲁·莫顿的观点

这是我在excel中解决问题并获得正确答案所采用的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; //for StreamReader and StreamWriter
using System.Text.RegularExpressions;
using System.Windows.Forms; 
using System.Globalization; //from two digit date to four digit date conversion.

namespace Experiment2
{
    class DemandRefundOnly
    {
      public line1 {get; set;}
      public Line3 {get; set;}
      DateTime dateTime;
      int FourDigitYear; 
      int Month; 
      int Day;
      DateTime dateTime;
      Regex Line3 = new Regex(@"(?<one>[0-9]{2}-[0-9]{2}-[0-9]{2})\s{1,20}114B\s{1,15}(?<two>\d{1,11})\s{1,15}(?<three>\d{1,11})\s{1,15}(?<four>\d{1,11})\s{1,30}(?<five>\d{1,11})");//Regex to capture data. //<one> catpures the date data.

      //Only the relevant date part is going to be shown in the output given.

      using (StreamReader Reader1 = new StreamReader(@"C:\Users\UK\data.txt"))
      { //StreamREader to read the input text file.
         using(StreamWriter Writer1 = new StreamWriter(@"C:\Users\Sample.csv"))
         { //StreamWriter to wrie to the output file.
            while((line1 = Reader1.ReadLine())!= null)
            { //to loop through the input file.
               MatchCollection matches = Line3.Matches(line1);
               foreach (Match m in matches)
               { //for...each to loop through and print the matches.
                  //Writer1.Write(m.Groups["one"].Value + ","); //this line modified with the following.


                 Day = Convert.ToInt32(m.Groups["one"].Value.Substring(0, 2));
                    //the above captures the first two digits date string contained in m.Groups["one"].Value and stores the first two characters as int to Day.
                 Month = Convert.ToInt32(m.Groups["one"].Value.Substring(3, 2));
                 FourDigitYear = Convert.ToInt32(m.Groups["one"].Value.Substring(6, 2));
                 FourDigitYear = CultureInfo.CurrentCulture.Calendar.ToFourDigitYear(FourDigitYear);
                 dateTime = new DateTime(FourDigitYear, Month, Day);
                 Writer1.WriteLine(dateTime);
               }
            }
         }
      }
   }
}

我尝试将新创建的输出文件导入Excel(其中有一列),日期以统一的方式正确显示。这对我来说是可以接受的,因为我们在印度使用斜线、破折号甚至点来分隔dd-mm-yy。这对我来说没关系。我还承认,我从Stackoverflow本身获得了四位数转换器代码行。特别感谢@AdrianHHH和@Andrew Morten,他们积极地为我花费了一定的宝贵时间。

文本文件中的正确输出是什么?在output.csv文件中(如果我用记事本打开),它显示为01-12-13,是dd-MM-yy格式。总是。问题是在excel中双击csv文件打开时。您需要为有问题的行提供输入字符串,例如3/5/2012。。。给出完整的输入行,您应该将CSV生成代码更改为ISO-8601格式的输出,以消除任何歧义。“
dd-MM-yy
”是您选择的最糟糕的日期格式之一!我说,在记事本中打开CSV文件,并显示该文件包含的内容。你似乎误解了你正在做的事情的两个阶段性质,以及需要展示中间阶段。这可能是一个好的解决方案。我只是在试验你回来之前所做的事情。@Unnikrishnan在我的手机上尝试了Excel上的csv后,我对这个想法没有多大希望,但可能Excel 2016做得更好。这可能是因为你必须在Windows中正确设置区域设置。莫顿的观察是正确的。我测试了莫顿的程序。并发现,如果我在excel中打开该文件,我将在计算机中以dd/MM/yyyy格式获取该文件。这可能因区域设置而异。我的意思是我将在我的计算机中以MM/dd/yyy格式获取它。日期统一显示在csv文件中。我检查了写入csv文件的1020个条目。似乎还可以使用ToSortDateString()从日期中删除时间部分;
4/5/2012 12:00:00 AM
4/5/2012 12:00:00 AM
4/9/2012 12:00:00 AM
4/9/2012 12:00:00 AM
4/9/2012 12:00:00 AM
4/9/2012 12:00:00 AM
4/9/2012 12:00:00 AM
4/12/2012 12:00:00 AM