生成Excel报告时需要日期和时间,以毫秒为单位 [英] Need date&time with millisecond while generating excel report

查看:72
本文介绍了生成Excel报告时需要日期和时间,以毫秒为单位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I am going to Log my process parameters in SQL and generate Excel Reports. The Programming is done in VB.Net

we are going to log Date_Time in 'YYYY-MM-DD HH:mm:ss.ms' example:'2018-11-27 21:41:24.170' (Here ms is milisec.) But while exporting with excel it comes in '27/11/18 21:41:24.000' not able to show millisecond data(here it is .170) . So, Can you please let me know how i can show date&Time including millisecond in Excel.

Excel Setting for Date Column : dd/mm/yy hh:mm:ss.000

Please find Vb.net program for your reference.

Please let me know your suggestions So,it will resolve my issue.<pre>

VB.Net Code *********

<pre lang="vb"><pre>Imports System.Data
Imports System.Data.SqlClient
' For th is need to add Microsoft Excel componant from project > Add Ref > Com
Imports Excelr = Microsoft.Office.Interop.Excel

Module Module1
    Dim conn As SqlConnection
    Dim path As String = "C:\mysettxtup\Connectionstring.txt"
    Dim objectreader As New System.IO.StreamReader(path)
    Dim connetionString As String

    Dim adpt As New SqlDataAdapter
    Dim ds As New DataSet

    ' used for excel report
    Dim r, c As Integer
    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub
    Sub Main()
        '----- Read SQl Connection from Text File------
        connetionString = objectreader.ReadLine
        conn = New SqlConnection(connetionString)
        'Dim trn_Log1, trn_Log2 As ADODB.Recordset
        '************************************************************************************************************
        ' Set the Format type and the CustomFormat string.
        'Start date 
        ' DateTimePickerST.Format = DateTimePickerFormat.Custom
        ' DateTimePickerST.CustomFormat = "MM/dd/yyyy H:mm"
        'Clear connection and dataset before open
        conn.Close()
        ds.Clear()

        'To handle exception use here Try catach
        Try
            'Open connection 
            conn.Open()
            'Dim query As String

            '  Dim query As String = "Select * from ProDataTbl1Sec where Date_Time between '" & RStartDate.Text & "'and'" & REndDate.Text & "'order by date_time asc"

            Dim query As String = "SELECT * FROM ProDataTbl1Sec WHERE Date_Time >= dateadd(hour,-24,getdate())"
            'Dim query As String = "SELECT * FROM ProDataTbl1Sec"

            adpt.SelectCommand = New SqlCommand(query, conn)

            ds = New DataSet("wincc")
            adpt.Fill(ds)


            Dim i, j As Integer

            ' Standard for Excel application
            Dim xlApp As Excelr.Application
            Dim xlWorkBook As Excelr.Workbook
            Dim xlWorkSheet As Excelr.Worksheet
            'Dim shXL As Excel.Worksheet
            'xlWorkSheet.Visible = True

            Dim misValue As Object = System.Reflection.Missing.Value


            ' Dim xlSourceRange As Excel.Range
            xlApp = New Excelr.Application

            ' ------- Read Sample Report Location from Text file ------

            'Dim path As String = "C:\Pall\mysetup\connectionstring.txt"
            'Dim objectreader As New System.IO.StreamReader(path)
            'connetionString = objectreader.ReadLine
            'conn = New SqlConnection(connetionString)

            Dim Srpath As String = "C:\mysettxtup\samplereport.txt"
            Dim Srobjectreader As New System.IO.StreamReader(Srpath)
            Dim Srpathstring As String = Srobjectreader.ReadLine


            ' ------- Read Sample Report Location from Text file  ------
            xlWorkBook = xlApp.Workbooks.Add(Srpathstring & "\SampleReport")

            ' ------- Save as Report Location from Text file  ------
            Dim Slrpath As String = "C:\mysettxtup\Savereport.txt"
            Dim Slrobjectreader As New System.IO.StreamReader(Slrpath)
            Dim Slrpathstring As String = Slrobjectreader.ReadLine

            'xlWorkSheet = xlWorkBook.Sheets("D:\Pall\Report\SampleReport")
            xlWorkSheet = xlWorkBook.Sheets("Report")

            r = ds.Tables(0).Rows.Count + 7 ' 7 add here because we start 1 record from 8th row
            c = ds.Tables(0).Columns.Count

            Console.WriteLine(r)
            Console.WriteLine(c)

            Console.WriteLine("Work in Process")

            ' Print Table Row with column of worksheet
            For i = 0 To ds.Tables(0).Rows.Count - 1
                'For j = 0 To ds.Tables(0).Columns.Count - 1
                For j = 0 To ds.Tables(0).Columns.Count - 1


                    xlWorkSheet.Cells(i + 8, j + 1) = ds.Tables(0).Rows(i).Item(j)
                    xlWorkSheet.Columns("A:I").EntireColumn.AutoFit()
                    'xlWorkSheet.Columns("A").EntireColumn.farmat()
                Next

                Console.WriteLine(i)
            Next
            ' Save Excel Sheet
            '~~> Save Worksheet file to the following location
            'xlWorkSheet.SaveAs("E:\VB\Report\vbexcel_" + currentdate.ToString() + "xlsx")
            Dim currentdate As String = String.Format("{0:ddMMyyyy-Hmm }", DateTime.Now)
            ' Excel Animation
            'xlWorkSheet.Columns("A:I").EntireColumn.AutoFit()
            With xlWorkSheet
                .Range("A2").Value() = "Date : " & currentdate
            End With

            ' ------- Save as Report Location from Text file  ------
            'RLocation.Text = " Report save in " & Slrpathstring
            xlWorkSheet.SaveAs(Slrpathstring & "\ParagDailyReport_" & currentdate & ".xlsx")

            xlWorkBook.Close()
            xlApp.Quit()

            releaseObject(xlApp)
            releaseObject(xlWorkBook)
            releaseObject(xlWorkSheet)

            'close connection , dadaptor and clear dataset
            conn.Close()
            adpt.Dispose()
            ds.Dispose()


        Catch ex As Exception

            MsgBox(ex.ToString())

        End Try
    End Sub

End Module





我的尝试:





What I have tried:

Please find Vb.net program for your reference.

Please let me know your suggestions So,it will resolve my issue

推荐答案

不要这样做像那样。永远不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。总是使用参数化查询。



连接字符串时会导致问题,因为SQL会收到如下命令:

Don't do it like that. Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'

就SQL而言,用户添加的引号会终止字符串,并且您会遇到问题。但情况可能更糟。如果我来并改为输入:x'; DROP TABLE MyTable; - 然后SQL收到一个非常不同的命令:

The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:

SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'

哪个SQL看作三个单独的命令:

Which SQL sees as three separate commands:

SELECT * FROM MyTable WHERE StreetAddress = 'x';

完全有效的SELECT

A perfectly valid SELECT

DROP TABLE MyTable;

完全有效的删除表格通讯和

A perfectly valid "delete the table" command

--'

其他一切都是评论。

所以它确实:选择任何匹配的行,从数据库中删除表,并忽略其他任何内容。



所以总是使用参数化查询!或者准备好经常从备份中恢复数据库。你定期做备份,不是吗?



你可能会发现,如果你将你的文本框解析为DateTime值 - 包括ms - 并将它们作为参数传递, Excel可以接受它们。

And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

You may well find that if you parse your textboxes to DateTime values - including ms - and pass those as parameters, Excel may accept them.


这篇关于生成Excel报告时需要日期和时间,以毫秒为单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆