【问题标题】:Copy date format cell to datatable excellibrary将日期格式单元格复制到数据表 excellibrary
【发布时间】:2014-09-29 11:32:43
【问题描述】:

我正在用 C# 开发一个程序,是一个桌面应用程序。 我有一个问题,我正在使用 excellibrary 打开一个 excel 并将数据复制到一个数据表中,但是我有一个日期格式为 mm/dd/yyyy 的单元格,但是当我在 datagridview 中显示数据表时,此信息更改为数字,例如:

02/07/1984 -> 30865

这是我的代码,希望有人能帮助我!

private DataTable ConvertToDataTable(string FilePath)
        {
            string file = FilePath;
            // open xls file
            Workbook book = Workbook.Open(file);
            Worksheet sheet = book.Worksheets[0];

            DataTable dt = new DataTable();
            // traverse rows by Index
            for (int rowIndex = sheet.Cells.FirstRowIndex; rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
            {

                Row row = sheet.Cells.GetRow(rowIndex);
                object[] temparray = new object[row.LastColIndex + 1];
                for (int colIndex = row.FirstColIndex;
                   colIndex <= row.LastColIndex; colIndex++)
                {
                    Cell cell = row.GetCell(colIndex);
                    temparray[colIndex] = cell.Value;
                }
                if (rowIndex == 0)
                {
                    foreach (object obj in temparray)
                    {
                        dt.Columns.Add(obj.ToString());
                    }
                }
                else
                {
                    dt.Rows.Add(temparray);
                }

            }

            return dt;
        }

【问题讨论】:

    标签: c# excel excellibrary


    【解决方案1】:

    您看到的数字是 OLE 自动化日期,您需要使用 DateTime.FromOADate Method 将该数字转换为 DateTime

    DateTime dt = DateTime.FromOADate(30865); //dt = {02/07/1984 12:00:00 AM}
    

    要在当前代码中使用该方法,您必须遍历每一列的值和日期索引,将值解析为 DateTime,然后将其添加到 DataTable

    【讨论】:

    • 谢谢,你的回答对我有帮助,希望其他遇到同样问题的人看到你的回答
    猜你喜欢
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 2014-02-11
    相关资源
    最近更新 更多