[英]How to convert Excel values to datetime format in C#
我正在嘗試使用Excel Interop從Excel工作表中提取數據。 這里使用范圍內的單元格包含日期/時間值。 我設法以文本形式獲取值,但如何將其轉換為可用於比較操作的數字或日期/時間格式?
using System;
using Excel = Microsoft.Office.Interop.Excel;
class Program
{
static void Main(string[] args)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
string str;
int rCnt = 0;
int cCnt = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open("Wind_Speed.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
// here I can get a string value... how to make it date/time
str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Text
Console.WriteLine(str);
Console.ReadLine();
}
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Console.ReadLine();
}
如果原始數據是Excel中的“日期”值(而不是文本),則應該能夠使用DateTime.FromOADate
方法提取該值並將其轉換為DateTime.FromOADate
:
double dateValue = range.Cells[rCnt, cCnt].Value2; // not "Text"
DateTime dateTime = DateTime.FromOADate(dateValue);
另請注意,使用Office互操作逐單元提取數據通常比將所有數據提取到一個大數組中然后在C#中處理該數組要慢得多:
range = xlWorkSheet.UsedRange;
object[,] rangeDate = (object[,])range.Value;
for (rCnt = 0; rCnt <= Array.GetLength(rangeDate, 0) ; rCnt++)
{
for (cCnt = 0; cCnt <= Array.GetLength(rangeDate, 1); cCnt++)
{
object value = rangeDate[rCnt, cCnt] ;
...
}
}
目前還不清楚您要問的是什么,但是可能您需要獲取價值,而不是文本
//some code here
{
var rangeValue = (range.Cells[rCnt, cCnt] as Excel.Range).Value
//do whatever you need
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.