【发布时间】:2019-03-06 16:10:52
【问题描述】:
从一个非常大的 Excel 文件中,我们循环并将 3 列中的值存储到变量中(uName(Row)、mgrName(Row)、title(Row))。从这个excel中,我们也得到了行数。
当我尝试使用 StringBuilder 创建一个单独的 .xls 文件以供稍后在应用程序中使用时,问题就出现了。我的代码如下所示:
Dim XLstring As System.Text.StringBuilder = New System.Text.StringBuilder
Dim newfile As System.IO.StreamWriter
Dim fileTitle
XLstring.Append("Name,Manager,Title" & vbCrLf)
For X As Integer = 2 To countrows
If X = countrows Then
MsgBox(countrows)
MsgBox(uName(X) & "," & mgrName(X) & "," & title(X))
End If
XLstring.Append(uName(X) & "," & mgrName(X) & "," & title(X) & vbCrLf)
Next
fileTitle = System.DateTime.Now.ToString("yy-MM-dd hh-mm-ss") & ".xls"
filePath2 = "myPath" & fileTitle
newfile = File.CreateText(filePath2)
newfile.WriteLine(XLstring)
这在大多数情况下都有效。我可以看到我正在使用 MsgBox 获取正确的行数以及最后一行中的正确信息。但是,当我打开生成的 .xls 文件时,文件末尾缺少条目。另外,如果我要改变
XLstring.Append("Name,Manager,Title" & vbCrLf)
类似
XLstring.Append("Name,Manager" & vbCrLf)
我从 Append 行中删除的确切字符数现在将成功显示在缺少信息的文件末尾。
使用这些功能是否有一些我不理解的奇怪功能?我完全迷失了,不理解这种行为。
【问题讨论】:
-
我将其重新标记为 VB.Net,因为它不是 VBA
-
你要关闭 newFile 来刷新它吗?
.WriteAllText更简单:docs.microsoft.com/en-us/dotnet/api/… -
@AlexK。所以我添加了“newfile.Flush()”这行似乎有效。您认为简单地添加它会导致任何其他问题吗?
标签: excel string vb.net append stringbuilder