【发布时间】:2009-05-11 05:39:17
【问题描述】:
我想从 Excel 创建一个 CSV 文件,其中字符串值应使用双引号,日期值应使用 MM/dd/yyyy 格式。所有数字和布尔值都应该不带引号。
我该怎么办?
【问题讨论】:
-
我可以建议以 ISO yyyy-MM-dd 格式存储日期吗?它将为您解决国际化问题。
我想从 Excel 创建一个 CSV 文件,其中字符串值应使用双引号,日期值应使用 MM/dd/yyyy 格式。所有数字和布尔值都应该不带引号。
我该怎么办?
【问题讨论】:
Excel 不允许您指定格式有点可怕。这是一个 MrExcel 链接,可能对您也有用。
http://www.mrexcel.com/forum/showthread.php?t=320531
这是该网站的代码:
Sub CSVFile()
Dim SrcRg As Range
Dim CurrRow As Range
Dim CurrCell As Range
Dim CurrTextStr As String
Dim ListSep As String
Dim FName As Variant
FName = Application.GetSaveAsFilename("", "CSV File (*.csv), *.csv")
If FName <> False Then
ListSep = Application.International(xlListSeparator)
If Selection.Cells.Count > 1 Then
Set SrcRg = Selection
Else
Set SrcRg = ActiveSheet.UsedRange
End If
Open FName For Output As #1
For Each CurrRow In SrcRg.Rows
CurrTextStr = ""
For Each CurrCell In CurrRow.Cells
CurrTextStr = CurrTextStr & """" & CurrCell.Value & """" & ListSep
Next
While Right(CurrTextStr, 1) = ListSep
CurrTextStr = Left(CurrTextStr, Len(CurrTextStr) - 1)
Wend
Print #1, CurrTextStr
Next
Close #1
End If
End Sub
【讨论】:
使用 VBA 更容易做到这一点。 Workbook 对象的 SaveAs 方法只允许您选择预定义的格式,xlCSV 不使用双引号分隔字符串。
在 VBA 中执行此操作:
Dim fileOut As Integer
fileOut = FreeFile
Open "C:\foo.csv" For Output As #fileOut
Write #fileOut, 14, "Stack Overflow", Date, True
Close #fileOut
(NB Date 是一个 VBA 语句,它返回当前系统日期作为子类型 Date 的 Variant)
如果您随后在记事本中检查该文件:
14,"堆栈溢出",#2009-05-12#,#TRUE#
字符串已按要求分隔,日期转换为通用格式,日期和布尔值均用#号分隔。
要在使用Input # 语句中读回数据,该语句将正确解释所有值。
如果你想写一行的一部分,然后再写完:
Write #fileOut, 14, "Stack Overflow";
Write #fileOut, Date, True
产生与原始程序相同的结果。第一条语句末尾的分号防止新行开始
嵌入双引号的字符串会导致问题,因此您需要删除或替换这些字符
【讨论】: