DataGrid读写txt文件

    技术2022-05-19  29

    工程|部件—>Microsoft DataGrid Control 6.0(SP6);工程|引用—>Microsoft Scripting Runtime;工程|部件—>Microsoft ADO Data Control 6.0窗体上放置两个按钮 一个dataGrid 一个ADODC 程序代码

            Option ExplicitDim rs As RecordsetConst ReadMode As String = 1Const WriteMode As String = 2Dim i As Integer

    Private Sub Command1_Click()Dim output As StringDim ans As Stringans = MsgBox("确定保存?", vbOKCancel)If ans = vbOK Thenrs.MoveFirst'将记录转换成字符串output = rs.GetString(adClipString, rs.RecordCount, vbTab, vbCrLf, "null") '文件输出数据OpenFile(WriteMode).Write (output) '将字符串写入文件ElseExit SubEnd IfEnd Sub

    Private Sub Command2_Click()Unload Me

    End Sub

    Private Sub Form_Load()If FoundRs(OpenFile(ReadMode)) Then Set DataGrid1.DataSource = rs Else MsgBox "打开不成功!" End IfEnd SubPrivate Function FoundRs(ts As TextStream) As Boolean  '创建记录集,并将txt文件中的数据显示Dim sOn Error GoTo perrorsSet rs = New Recordset'以下为创建标题栏字段With rs  .Fields.Append "stuid", adBSTR  .Fields.Append "wordid", adBSTR  .Fields.Append "excelid", adBSTR  .Fields.Append "wordsubmit", adBSTR  .Fields.Append "excelsubmit", adBSTR  .OpenEnd With'将文本文件数据读入到rs中Do While ts.AtEndOfStream <> Trues = Split(ts.ReadLine, vbTab) 'txt文件通过tab键分割With rs.AddNew '增加新的一行'逐行读取txt文件For i = 0 To 4 .Fields(i) = s(i) Next .Update End With Loop '成功返回true FoundRs = True Exit Functionperrors: FoundRs = FalseEnd FunctionPrivate Function OpenFile(x As String) As TextStreamDim fso As New FileSystemObjectDim fil As FileDim ts As TextStreamDim s As StringDim strPath As StringstrPath = "D:" & "/paperuser.txt" '设置文件路径'以下为打开文件Set fil = fso.GetFile(strPath) '获取txt文件的指针Set ts = fil.OpenAsTextStream(x) '以文本流的方式读取数据放入ts中Set OpenFile = tsEnd Function

     


    最新回复(0)