繁体   English   中英

C#Excel DateTime导出

[英]C# Excel DateTime Export

我需要将一些数据导出到Excel工作表。 数据由数据时间值和读数建立。 我的问题是,当我导出日期时间值时,它们将其格式更改为美国日期而不是英国。

我尝试通过将格式添加到日期时间值所在的范围来对其进行排序,现在它甚至变得更有趣了。 我注意到直到9月,它都以英国格式处理日期时间值,但此后更改为美国时间。

打开excel文件后,我在应用程序中插入单元格的格式仅适用于美国格式。

请查看我的代码,它可能会帮助您解决我的问题:

        // Get dimensions of the 2-d array
        int rowCount = data2.GetLength(0);
        int columnCount = data2.GetLength(1);
        // Get an Excel Range of the same dimensions
        Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
        range = range.get_Resize(rowCount, columnCount);
        // Assign the 2-d array to the Excel Range
        range.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, data2);

        // Reset the range
        range = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
        range = range.get_Resize(rowCount, 1);
        // Set the format type of the range
        range.NumberFormat = "DD/MMM/YYYY hh:mm:ss";

编辑解决方案在adrianm帮助下,这是解决方案代码:

我保留了先前包含的代码,但是我更改了创建data2对象数组(object [,] data2)的代码。

        //create the empty array
        var result = new object[data.Count, data[0].Count];
        //insert all of the values in it
        for (int i = 0; i < data.Count; i++)
        {
            for (int j = 0; j < data[i].Count; j++)
            {
                if (j < data[i].Count)
                    result[i, j] = data[i][j];
                else
                    result[i, j] = " ";
            }
        }

        //change the date time values to doubles which are 
        //in the first column after the first entry
        for (int i = 1; i < data.Count; i++)
        {
            result[i, 0] = (Convert.ToDateTime(result[i, 0])).ToOADate();
        }

            return result;

尝试像这样将整个列格式化为日期列

range.EntireColumn.NumberFormat =“ DD / MM / YYYY”;

希望这会起作用

在adrianm的帮助下,这是解决方案代码:

我保留了先前包含的代码,但是我更改了创建data2对象数组(object [,] data2)的代码。

    //create the empty array
    var result = new object[data.Count, data[0].Count];
    //insert all of the values in it
    for (int i = 0; i < data.Count; i++)
    {
        for (int j = 0; j < data[i].Count; j++)
        {
            if (j < data[i].Count)
                result[i, j] = data[i][j];
            else
                result[i, j] = " ";
        }
    }

    //change the date time values to doubles which are 
    //in the first column after the first entry
    for (int i = 1; i < data.Count; i++)
    {
        result[i, 0] = (Convert.ToDateTime(result[i, 0])).ToOADate();
    }

        return result;

暂无
暂无

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

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