求助 提取excel 某个字段相关数据 并生成其字段的新excel文件,以下代码提取数据打开后是乱码,
#include <Excel.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <FileConstants.au3>
#include <Array.au3>
Global $hGUI, $hInput1, $hInput2, $hInput3, $hButton
$hGUI = GUICreate("Excel Data Extraction", 600, 400)
GUICtrlCreateLabel("Source File Path:", 10, 10)
$hInput1 = GUICtrlCreateInput("", 10, 30, 480, 20)
$hButton1 = GUICtrlCreateButton("Browse", 500, 30, 80, 20)
GUICtrlCreateLabel("Save Path:", 10, 60)
$hInput2 = GUICtrlCreateInput("", 10, 80, 480, 20)
$hButton2 = GUICtrlCreateButton("Browse", 500, 80, 80, 20)
GUICtrlCreateLabel("Extracted Field:", 10, 110)
$hInput3 = GUICtrlCreateInput("", 10, 130, 580, 20)
$hButton = GUICtrlCreateButton("Extract", 260, 160, 80, 30)
GUISetState(@SW_SHOW)
While 1
Switch GUIGetMsg()
Case $GUI_EVENT_CLOSE
ExitLoop
Case $hButton1
SelectSourceFile()
Case $hButton2
SelectSavePath()
Case $hButton
ExtractData()
EndSwitch
WEnd
GUIDelete($hGUI)
Func SelectSourceFile()
Local $sSourceFile = FileOpenDialog("Select Source File", "", "Excel Files (*.xls;*.xlsx)|All Files (*.*)", $FD_FILEMUSTEXIST)
If @error Then Return
GUICtrlSetData($hInput1, $sSourceFile)
EndFunc
Func SelectSavePath()
Local $sSavePath = FileSelectFolder("Select Save Path", "")
If @error Then Return
GUICtrlSetData($hInput2, $sSavePath)
EndFunc
Func ExtractData()
Local $sSourceFile = GUICtrlRead($hInput1)
Local $sSavePath = GUICtrlRead($hInput2)
Local $sFieldName = GUICtrlRead($hInput3)
If Not FileExists($sSourceFile) Then
MsgBox(16, "Error", "Source file does not exist.")
Return
EndIf
Local $hFile = FileOpen($sSourceFile, $FO_READ)
If $hFile = -1 Then
MsgBox(16, "Error", "Failed to open file.")
Return
EndIf
Local $aFieldNames = StringSplit(FileReadLine($hFile), ",")
Local $sFileName = $sSavePath & "\" & $sFieldName & ".xlsx"
$sFileName = StringReplace($sFileName, "\", "/") ; 替换路径中的反斜杠为正斜杠
Local $hOutputFile = FileOpen($sFileName, BitOR($FO_OVERWRITE, $FO_UTF8))
If $hOutputFile = -1 Then
MsgBox(16, "Error", "Failed to create file.")
FileClose($hFile)
Return
EndIf
FileWriteLine($hOutputFile, _ArrayToString($aFieldNames, ","))
Local $sLine
While 1
$sLine = FileReadLine($hFile)
If @error Then ExitLoop
Local $aLineData = StringSplit($sLine, ",")
If StringInStr($sLine, $sFieldName) Then
FileWriteLine($hOutputFile, _ArrayToString($aLineData, ","))
EndIf
WEnd
FileClose($hFile)
FileClose($hOutputFile)
MsgBox(64, "Success", "Data extracted and saved to " & $sFileName)
EndFunc
|