如何从Excel文件中有效地检索时间值?

时间:2014-11-25 11:21:28

标签: c# excel

我需要从Excel文件中检索时间值。

以下是文件的结构:

ID | COLUMN_1  | COLUMN_2 
1  | 00:10:00  | 00:08:23
2  | 00:23:00  | 01:45:00
3  | 02:01:45  | 01:23:35   
...

因此我的Excel工作簿包含很少的时间列(格式为“小时”),但当我将格式更改为“标准”时,它会显示浮点数。

我使用C#创建了一个脚本来阅读这个文档。 我需要将列的内容作为时间复制到另一个Excel文件。 该脚本处理所有列并填充另一个Excel工作簿,但INSERT不起作用,因为它尝试将浮点数插入时间字段。 如何获得时间价值?

foreach (DataRow row in rawDataTable.Rows)
{
    // INSERT INTO ....
    row[1] // Time column. How to get a Time value ?
    // I retrieved something like 0,00684027777777778, I need something formatted as HH:mm:ss
    // Because I need to copy the Time value to a Time field in another Excel workbook.
}

2 个答案:

答案 0 :(得分:0)

Excel日期值是自191年1月1日以来的天数,所以如果你有一个没有日期的时间值,你可以乘以86400得到秒。

但是,如果要复制在工作簿之间按时间格式化的单元格,则不必转换它,只需将其复制为double并正确格式化单元格。

答案 1 :(得分:0)

让我试着回答你的问题。保存数据的关键是格式化,就像@ grahamj42说的那样。 基本上,我创建了一个按钮。在点击处理程序上,我从源Excel应用程序读取数据,并将其保存到新创建的目标Excel应用程序。我加入了笔记,所以非常清楚。

您必须在页面顶部包含以下指令:

using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;

这是完整的代码:

public class ExcelRow
{
    public int ID { get; set; }
    public string Date1 { get; set; }
    public string Date2 { get; set; }
}

protected void btnCopy_Click(object sender, EventArgs e)
{
    //source excel app
    var sourceExcelApp = new Excel.Application()
    {
        Visible = false,
        ScreenUpdating = false,
        DisplayAlerts = false
    };

    //get source workBook - assuming that path of source excel file is in C:\\
    Excel.Workbook sourceWorkbook = sourceExcelApp.Workbooks.Open(@"c:\\source.xls",
       Missing.Value, Missing.Value, Missing.Value,
       Missing.Value, Missing.Value, Missing.Value, Missing.Value,
       Missing.Value, Missing.Value, Missing.Value, Missing.Value,
       Missing.Value, Missing.Value, Missing.Value);

    //assuming that data is inside of first worksheet (WorkSheets[1])
    Excel._Worksheet sourceWorksheet = (Excel._Worksheet)sourceWorkbook.Worksheets[1];

    //get column ranges including header names
    Excel.Range ID = sourceWorksheet.Range["A1"];
    Excel.Range date1 = sourceWorksheet.Range["B1"];
    Excel.Range date2 = sourceWorksheet.Range["C1"];

    //get last row in table(from A1 to last cell in C column)
    int lastRowCount = sourceWorksheet.UsedRange.Rows.Count;

    var excelRow = new ExcelRow();
    List<ExcelRow> excelRowList = new List<ExcelRow>();
    //note that we start iteration from 1 in order not to read first cells values
    for (int i = 1; i < lastRowCount; i++)
    {
        excelRowList.Add(new ExcelRow
        {
            ID = int.Parse(ID.Offset[i, 0].Value2.ToString()),
            Date1 = date1.Offset[i, 0].Value2.ToString(),
            Date2 = date2.Offset[i, 0].Value2.ToString()
        });
    }


    //create new instance of target Excel app and
    var targetExcelApp = new Excel.Application();
    targetExcelApp.Visible = true;
    Excel.Workbook targetWorkbook = targetExcelApp.Workbooks.Add();
    Excel._Worksheet targetWorksheet = (Excel._Worksheet)targetExcelApp.ActiveSheet;
    //set columns headers titles
    targetWorksheet.Cells[1, "A"] = "ID";
    targetWorksheet.Cells[1, "B"] = "COLUMN_1";
    targetWorksheet.Cells[1, "C"] = "COLUMN_2";

    //formating target rows
    targetWorksheet.Range[String.Concat("B1:", "B", lastRowCount)].NumberFormat = "@";
    targetWorksheet.Range[String.Concat("C1:", "C", lastRowCount)].NumberFormat = "@";

    //fill targeted rows
    int counter = 1;
    foreach (var row in excelRowList)
    {
        counter++;

        targetWorksheet.Cells[counter, "A"] = row.ID;
        targetWorksheet.Cells[counter, "B"] = row.Date1;
        targetWorksheet.Cells[counter, "C"] = row.Date2;
    }

    //autofit columns width
    targetWorksheet.Columns.AutoFit();
    //save data to new excel app
    targetWorksheet.SaveAs("target", Type.Missing,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    //release resources
    ReleaseObject(sourceWorksheet);
    ReleaseObject(sourceWorkbook);
    ReleaseObject(sourceExcelApp);

    ReleaseObject(targetWorksheet);
    ReleaseObject(targetWorkbook);
    ReleaseObject(targetExcelApp);
}

这是重新启动Excel资源的方法:

public static void ReleaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    finally
    {
        GC.Collect();
    }
}