C#正在获取excel值日期

本文关键字:日期 excel 获取 | 更新日期: 2023-09-27 17:59:49

我需要检索一个excel日期列。我的第一列"A"值的格式如下6/20/2016 10:44。使用以这种格式检索列"A"没有问题

using DocumentFormat.OpenXml;
double d = double.Parse(theCell.InnerText);
DateTime conv = DateTime.FromOADate(d).Date;

我的第二列"B"的格式为6/20/2016.,没有时间,只有日期。但我的问题是当我尝试以下代码时:

using DocumentFormat.OpenXml;
double d = double.Parse(theCell.InnerText);
DateTime conv = DateTime.FromOADate(d).Date;

Cell.InnerText值为1455

我有不同的价值观。该值变为12/25/1903 12:00:00 AM

如何使用这种日期格式6/30/2016检索excel值?

C#正在获取excel值日期

我从这里找到了一些代码并对其进行了修改:从excel文件中打开xml读取

我的想法和Hambone的想法相同,即Excel单元格中有其他内容,或者你没有读取你认为的单元格。

这是我正在使用的代码,它对我有效:

using System;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace ConsoleApplication1
{
    class Program
    {
        private static void Main(string[] args)
        {
            var filePath = @"c:'xyz'stack_c_Sharp.xlsx";
            using (var document = SpreadsheetDocument.Open(filePath, false))
            {
                var workbookPart = document.WorkbookPart;
                var workbook = workbookPart.Workbook;
                var sheets = workbook.Descendants<Sheet>();
                foreach (var sheet in sheets)
                {
                    var worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
                    var sharedStringPart = workbookPart.SharedStringTablePart;
                    string text;
                    var rows = worksheetPart.Worksheet.Descendants<Row>();
                    foreach (var row in rows)
                    {
                        Console.WriteLine();
                        int count = row.Elements<Cell>().Count();
                        foreach (Cell theCell in row.Elements<Cell>())
                        {
                            text = theCell.CellValue.InnerText;
                            double d = double.Parse(theCell.InnerText);
                            DateTime conv = DateTime.FromOADate(d).Date;
                            Console.Write(text + " ");
                            Console.Write(conv + " ");
                        }
                    }
                }
                Console.ReadLine();
            }

        }
    }
}

我在VS2022上调试时打开了该文件,遇到了同样的问题。尝试关闭文件。