如何實現數據從 txt/word 自動導入到excel中

有時候我們需要把txt文檔或者word文檔中的資料導入到excel中去,但是採用copy/paste方式將是非常麻煩的。那麼有沒有辦法採用 自動化方式來導入資料到excle中呢?AutoIt提供了一種非常方便的解決方案。

AutoIt提供了一個寫excel的函 數:_ExcelWriteCell($oExcel, $sValue, $sRangeOrRow, $iColumn = 1)

第一 個參數爲$oExcel = _ExcelBookNew()或者$oExcel = _ExcelBookOpen()返回的對象。第二個參數是填入excel的數值,第三個和第四個參數是定義填入的位置。 所以我們只要用一個fileopen()函數讀入資料數據,再根據要求填入相應的位置就可以了。 用一個循環語句就可以非常輕鬆的完成文檔的copy了哦。下面這個是我下的一個腳本,用於從txt文檔中導出數據到excel中。非常的方便。

 

#include <Excel.au3>
$path = $Cmdline[1]
$saveas = $Cmdline[2]
$nHtmlFile = FileOpen($path, 0) ;   temp.txt 爲你縮寫的txt格式的case
$oExcel = _ExcelBookNew()
$low = 1
$string = ""
$temp = "[Preconditions]" & @CRLF & @CRLF & "[Steps]" & @CRLF & @CRLF & "[Expected Results]" & @CRLF & @CRLF
$flag = 1

While 1
    $line = FileReadLine($nHtmlFile)
    If @error = -1 Then
        FileClose($nHtmlFile)
        _ExcelWriteCell($oExcel, $string, $low, 2)
        _ExcelBookSaveAs($oExcel, $saveas, "xls", 0, 1) ; Now we save it into the temp directory; overwrite existing file if necessary
        _ExcelBookClose($oExcel, 1, 0) ; And finally we close out
        Exit
    EndIf
    $stringleft1 = StringLeft($line, 5)
    If StringInStr($stringleft1, '>') Then
        If $flag = 1 Then
            _ExcelWriteCell($oExcel, $line, $low + 1, 1) ;Write to the Cell
        Else
            _ExcelWriteCell($oExcel, $temp, $low, 2)
            $flag = 1
            _ExcelWriteCell($oExcel, $line, $low + 1, 1)
        EndIf
    Else
        Do
            $string &= $line & @CRLF
            $line = FileReadLine($nHtmlFile)
            If @error = -1 Then
                FileClose($nHtmlFile)
                _ExcelWriteCell($oExcel, $string, $low, 2)
                _ExcelBookSaveAs($oExcel, $saveas, "xls", 0, 1) ; Now we save it into the temp directory; overwrite existing file if necessary
                _ExcelBookClose($oExcel, 1, 0) ; And finally we close out
                Exit
            EndIf
            $stringleft1 = StringLeft($line, 10)
            _ReduceMemory(@AutoItPID)
        Until StringInStr($stringleft1, '>')
        _ExcelWriteCell($oExcel, $string, $low, 2) ;Write to the Cell
        $string = ""
        _ExcelWriteCell($oExcel, $line, $low + 1, 1) ;Write to the Cell
        $flag = 2
    EndIf

    $low = $low + 1
WEnd

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章