【发布时间】:2021-01-31 13:51:58
【问题描述】:
我想创建一个报告软件,在其中通过用户表单中的 datepicker 工具在用户指定的日期检索日期。我想知道如何实现代码以获得结果。
这是我的代码...请帮助我。我是新手
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private conn As New SqlConnection
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
conn.ConnectionString = "Data Source=ROG\SQLEXPRESS;Initial Catalog=GKEAPL;Integrated Security=True;"
conn.Open()
MsgBox("Connected")
Catch ex As Exception
MsgBox("Could Not connect")
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim officeexcel As New Microsoft.Office.Interop.Excel.Application
officeexcel = CreateObject("Excel.Application")
Dim workbook As Object = officeexcel.Workbooks.Add("D:\GKEAPL\project 1\gk format.xltx")
officeexcel.Visible = True
Dim da As New SqlDataAdapter
Dim ds As New DataSet
da = New SqlDataAdapter("SELECT FeedWaterTankLevelFWST101,
FeedFlowFT101,
ClearWaterTankLevelCWST201,
TMFilPressurePT201,
TMFolPressurePT202,
HPPilPressurePT203,
MembraneilPressurePT204,
MembraneolPressurePT205,
PermeateFlowFT201,
RejectFlowFT202
FROM DATA1 WHERE(DATEnTIME >='2020-12-18 11:06:30.000' AND DATEnTIME <= '2020-12-19 10:07:31.000')", conn)
da.Fill(ds, "DATA1")
For i As Integer = 0 To ds.Tables("DATA1").Rows.Count - 1
With officeexcel
.Range("Sheet2!B" + (i + 7).ToString).Value = ds.Tables("DATA1").Rows(i).Item(0).ToString
.Range("Sheet2!C" + (i + 7).ToString).Value = ds.Tables("DATA1").Rows(i).Item(1).ToString
.Range("Sheet2!D" + (i + 7).ToString).Value = ds.Tables("DATA1").Rows(i).Item(2).ToString
.Range("Sheet2!E" + (i + 7).ToString).Value = ds.Tables("DATA1").Rows(i).Item(3).ToString
.Range("Sheet1!F" + (i + 7).ToString).Value = ds.Tables("DATA1").Rows(i).Item(4).ToString
.Range("Sheet1!G" + (i + 7).ToString).Value = ds.Tables("DATA1").Rows(i).Item(5).ToString
.Range("Sheet1!H" + (i + 7).ToString).Value = ds.Tables("DATA1").Rows(i).Item(6).ToString
.Range("Sheet1!I" + (i + 7).ToString).Value = ds.Tables("DATA1").Rows(i).Item(7).ToString
.Range("Sheet1!J" + (i + 7).ToString).Value = ds.Tables("DATA1").Rows(i).Item(8).ToString
.Range("Sheet1!K" + (i + 7).ToString).Value = ds.Tables("DATA1").Rows(i).Item(9).ToString
End With
Next
officeexcel = Nothing
workbook = Nothing
Catch ex As Exception
End Try
End Sub
Private Sub Report_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DateTimePicker1.CustomFormat = "YYYY-MMMM-DD"
End Sub
End Class
【问题讨论】:
-
有什么问题?你收到错误了吗?在哪里和什么?如果它根本没有按预期执行,请说明原因。
-
连接必须被关闭和释放,所以它们只能在使用它们的方法中创建。
-
不要写空的 Catch 块。他们只会吞下错误。
-
您永远不会使用 DataAdapter 和 DataSet 提供的额外功能。只需使用命令和数据表。
-
@Mary 实际上,我不知道如何实现日期时间选择器。当我将日期直接放在查询中时,我确实得到了输出,但是在放置变量而不是日期时,我没有在 excel 上得到输出
标签: c# sql-server excel vb.net export-to-excel