我正在使用此过程将单元格区域导出到JSON。
Sub export_json(mysheet As Worksheet, myrange As String)
Dim fs As Object
Dim jsonfile
Dim rangetoexport As Range
Dim rowcounter As Long
Dim columncounter As Long
Dim linedata As String
Dim path As String
Dim fname As String
Set rangetoexport = mysheet.Range(myrange)
path = ThisWorkbook.path & "\"
fname = clean_filename(myrange, "") & ".json"
Set fs = CreateObject("Scripting.FileSystemObject")
Set jsonfile = fs.CreateTextFile(path & fname, True)
linedata = "{""Output"": ["
jsonfile.WriteLine linedata
For rowcounter = 2 To rangetoexport.Rows.Count
linedata = ""
For columncounter = 1 To rangetoexport.Columns.Count
linedata = linedata & """" & rangetoexport.Cells(1, columncounter) & """" & ":" & """" & rangetoexport.Cells(rowcounter, columncounter) & """" & ","
Next
linedata = Left(linedata, Len(linedata) - 1)
If rowcounter = rangetoexport.Rows.Count Then
linedata = "{" & linedata & "}"
Else
linedata = "{" & linedata & "},"
End If
jsonfile.WriteLine linedata
Next
linedata = "]}"
jsonfile.WriteLine linedata
jsonfile.Close
Set fs = Nothing
End Sub
但是,如果单元格值包含双引号“,则JSON文件的输出将损坏。有关如何解决此问题的任何想法?
答案 0 :(得分:1)
您需要使用斜杠将双引号转义。
For columncounter = 1 To rangetoexport.Columns.Count
linedata = linedata & """" & Replace(rangetoexport.Cells(1, columncounter), """", "\""") & """" & ":" & """" _
& Replace(rangetoexport.Cells(rowcounter, columncounter), """", "\""") & """" & ","
Next
此答案提供有关转义json的更多详细信息。 https://stackoverflow.com/a/19176131/7182460