繁体   English   中英

将日期格式的单元格复制到数据表中

[英]Copy date format cell to datatable excellibrary

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

1984年2月7日-> 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;
        }

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM