簡體   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