c# - 将日期格式单元格复制到数据表excellary

标签 c# excel excellibrary

我正在用 C# 开发一个程序,是一个桌面应用程序。 我有一个问题,我正在使用 excellbrary 打开 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

关于c# - 将日期格式单元格复制到数据表excellary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25161952/

相关文章:

c# - 我可以在 EF core asp.net 中使用相同模型创建多个表吗

C# 如何调整图像大小并以尽可能高的质量保存它们 - 批处理作业

C#:为什么忽略此代码?

r - readxl(将excel文件导入R)错误

excel - 自动计算特定日期的最低和最高温度

vba - 如何在VBA中更改用户窗体的标题栏文本?

c# - 使用excellary设置行高

c# - 无法打开用 excelLibrary 生成的 excel 文件

c# - Ncrunch 所有测试首次运行都通过,但在代码更改后以及按下“运行所有”按钮时失败

asp.net - 如何使用DataTable和ExcelLibrary创建Excel工作表?