AU3代码,发EXE怕有人说病毒
Func WriteToExcelCellsFromTXT($sFilePath, $sTxtFile, $sOutputPath = "")
If Not FileExists($sFilePath) Or Not FileExists($sTxtFile) Then Return False
; 如果未指定输出路径,则使用模板文件路径
If $sOutputPath = "" Then
$sOutputPath = $sFilePath
EndIf
; 读取TXT文件内容
Local $hFile = FileOpen($sTxtFile, 0) ; 0 = 只读模式
If $hFile = -1 Then Return False
Local $sJsonContent = FileRead($hFile)
FileClose($hFile)
; 解析JSON内容
Local $aCellData = ParseSimpleJSON($sJsonContent)
If @error Then Return False
Local $oExcel = ObjCreate("Excel.Application")
If @error Then Return False
$oExcel.DisplayAlerts = False
$oExcel.ScreenUpdating = False
Local $oWorkbook = $oExcel.Workbooks.Open($sFilePath)
If @error Then
$oExcel.Quit()
Return False
EndIf
Local $oWorksheet = $oWorkbook.ActiveSheet
; 遍历所有单元格数据并写入
For $i = 0 To UBound($aCellData) - 1
Local $sCell = $aCellData[$i][0]
Local $sContent = $aCellData[$i][1]
; 写入内容到指定单元格
$oWorksheet.Range($sCell).Value = $sContent
Next
; 保存到指定路径
$oWorkbook.SaveAs($sOutputPath)
$oWorkbook.Close()
$oExcel.Quit()
Return True
EndFunc
; 解析简单的JSON格式 [{"A5": "内容1","B5": "内容2"},{"A6": "内容3","B6": "内容4"}]
Func ParseSimpleJSON($sJson)
; 去除空格和换行
$sJson = StringReplace($sJson, @CR, "")
$sJson = StringReplace($sJson, @LF, "")
$sJson = StringStripWS($sJson, 8) ; 去除所有空格
; 检查基本格式
If Not StringLeft($sJson, 2) = "[{" Or Not StringRight($sJson, 2) = "}]" Then
Return SetError(1, 0, 0)
EndIf
; 移除外层的方括号
$sJson = StringMid($sJson, 3, StringLen($sJson) - 4)
; 分割对象
Local $aObjects = StringSplit($sJson, "},{", 1) ; 1 = 整个字符串分割
If @error Then Return SetError(2, 0, 0)
Local $aResult[0][2]
For $i = 1 To $aObjects[0]
Local $sObject = $aObjects[$i]
; 分割键值对
Local $aPairs = StringSplit($sObject, ",", 1)
If @error Then ContinueLoop
For $j = 1 To $aPairs[0]
Local $sPair = $aPairs[$j]
; 分割键和值
Local $aKeyValue = StringSplit($sPair, ":", 1)
If $aKeyValue[0] <> 2 Then ContinueLoop
; 提取键(单元格位置)
Local $sKey = $aKeyValue[1]
$sKey = StringReplace($sKey, '"', "")
; 提取值(内容)
Local $sValue = $aKeyValue[2]
$sValue = StringReplace($sValue, '"', "")
; 添加到结果数组
Local $iSize = UBound($aResult)
ReDim $aResult[$iSize + 1][2]
$aResult[$iSize][0] = $sKey
$aResult[$iSize][1] = $sValue
Next
Next
Return $aResult
EndFunc
; 使用示例 |