我搜索了很多,但是大多数结果都与excel有关。因此我找不到答案的线索。
我正在尝试通过ms access2010做到这一点:
我在第一行中有几个带有标头的csv文件。所有字段都由分隔,并且都是字符串(双引号,在双引号中有很多)。
我不知道每个csv文件中有多少列。 我想在第一行(标题)和第二行之间插入新行。
我如何找出csv文件有多少列? 以及如何在第二行添加新的文本行?
答案 0 :(得分:1)
FileSystemObject 是执行此类任务的出色工具:
Public Function InsertLine()
Const TmpExtension As String = ".tmp"
Const BakExtension As String = ".bak"
Dim FileSystemObject As Scripting.FileSystemObject
Dim SourceStream As Scripting.TextStream
Dim TargetStream As Scripting.TextStream
Dim Fields As Variant
Dim Values As Variant
Dim FieldCount As Long
Dim Item As Long
Dim Field As String
Dim FileName As String
Dim BaseName As String
Dim TempFileName As String
Dim Path As String
Dim Extension As String
Dim DotExtension As String
Dim TextLine As String
Set FileSystemObject = New Scripting.FileSystemObject
' File to modify.
FileName = "c:\test\timezone.csv"
BaseName = FileSystemObject.GetBaseName(FileName)
Extension = FileSystemObject.GetExtensionName(FileName)
Path = FileSystemObject.GetParentFolderName(FileName)
DotExtension = "." & Extension
TempFileName = BaseName & TmpExtension
Set SourceStream = FileSystemObject.OpenTextFile(FileName, ForReading)
Set TargetStream = FileSystemObject.CreateTextFile(TempFileName, ForWriting)
' Read header line.
TextLine = SourceStream.ReadLine
' Copy header line.
TargetStream.WriteLine TextLine
' Create line two.
Fields = Split(TextLine, ",")
' FYI.
FieldCount = UBound(Fields)
' Array to hold values.
Values = Fields
For Item = LBound(Fields) To UBound(Fields)
Select Case Item
Case 0
Field = "SomeValue"
Case 1
Field = "OtherValue"
Case 2
Field = "YetAValue"
' etc.
Case Else
Field = CStr(Item)
End Select
Values(Item) = Chr(34) & Field & Chr(34)
Next
' Write line two.
TargetStream.WriteLine Join(Values, ",")
' Copy remaining lines.
While Not SourceStream.AtEndOfStream
TargetStream.WriteLine SourceStream.ReadLine
Wend
' Close files.
SourceStream.Close
TargetStream.Close
' Rename files.
FileSystemObject.MoveFile FileName, FileSystemObject.BuildPath(Path, BaseName & BakExtension)
FileSystemObject.MoveFile TempFileName, FileSystemObject.BuildPath(Path, BaseName & DotExtension)
End Function
需要将引用设置为: Microsoft.Scripting.Runtime
答案 1 :(得分:-3)
只需记录一个Macro即可为您完成工作。我做到了,下面得到了这段代码。
NaN