Jump to content

Tab formating function


SamG
 Share

Recommended Posts

Hi, folks-

I am not a "real" programmer. Just a poor imitation.....

I have some visual basic code that I want to port over to AutoIT. I know this is going to be a lot of manual re-writring...

One of the "simple" formatting functions I need is to tab over X number of spaces when creating an output text file using fixed fonts, where I want columns of information to line up vertically. The old BASIC tab(xx) function, where you can write or print out text is what I am looking for. Oddly, I see no such function in AutoIt.

-------- PARTS CONSUMED ----------- ---- PARTS BACK TO STOCK (29T) ----

PN QTY DESCRIPTION PN QTY DESCRIPTION

======= ==== ====================== ======= ==== ======================

99Y1466 1 4444 Mod 745 80Y2886 1 4444 Mod 745

78P1854 1 2G SODIMM BULK# (PEW)

99Y1418 1 DVD ESD shield

99Y1420 1 Bucket- HDD lower

99Y1420 1 Bucket- HDD

99Y1424 1 500G Drive Kit*1(PEW)

99Y1424 1 500G Drive Kit*2(PEW)

45T9047 1 Front USB blank shield 45T9026 1 Front USB Cable

46N5296 1 Front USB card

46N2140 1 M3 screw

I would use the FileWriteLine command. I'm looking for a "@tab" function to tab over to the X or Y columns, just like the BASIC TAB function.

I admit that this may not be the best programming language choice. But I use AutoIt in other areas, and this would work for me...

Any suggestions? Thanks.

SamG

Link to comment
Share on other sites

SamG,

This may be of some use to you. At the very least you can adapt the technique to whatever you are doing.

; #FUNCTION# ======================================================================================
; Name ................: _print2d_array($str,$del,$output_file_name)
; Description .........: create a formatted text file from a 2d array
; Syntax ..............: _print2d_array($str, $del)
; Parameters ..........: $str - string to split
;                        $del - the delimter for columns
;                        $output_file_name - fully qualified output file name
; =================================================================================================
Func _print2d_array($str,$del,$output_file_name)
$str = stringregexpreplace($str,@crlf,@lf)
Local $a10 = StringSplit($str,@lf,3), $numcols = 0, $a20, $matrix = ""
; find max number of columns
For $i = 0 To UBound($a10) - 1
$a20 = StringSplit($a10[$i],$del)
if ubound($a20) > $numcols then $numcols = ubound($a20)
Next
; find max size of each column
local $colsize[$numcols]
For $i = 0 To UBound($a10) - 1
$a20 = StringSplit($a10[$i],$del)
For $j = 0 To $a20[0]
If StringLen($a20[$j]) > $colsize[$j] Then $colsize[$j] = StringLen($a20[$j]) + 5
Next
Next
; now format the output line
For $i = 0 To UBound($a10) - 1
$a20 = StringSplit($a10[$i],$del)
For $j = 0 To $a20[0]
$matrix &= StringFormat("%-" & $colsize[$j] & "s",$a20[$j]) & "|"
Next
$matrix &= @CRLF
next
; and finally write the output file
local $hfl = FileOpen($output_file_name,2)
FileWrite($hfl,$matrix)
FileClose($hfl)
$hfl = 0
endfunc

kylomas

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

SamG,

Cleaned / corrected the comments and provided an example. Change to output file name and this should run as is.

#include <Array.au3>
Opt("MustDeclareVars", 1)
local $string = "12345:a100:a200:9876:0:dfgh" & @crlf & _
    "string:z43:%:6:0" & @crlf & _
    "str:z:%the:9876:0:dfgh:what:the :hell" & @crlf & _
    "basketball" & @crlf & @crlf & "this:is:an:example:row:following1234567890:a:blank:row" & @lf & "123456789:for:@lf:mixed:with:@CRLF"
local $result_array = _stringsplit2d($string,":")
_arraydisplay($result_array)
 _print2d_array($string,":","k:sdtemptest.txt")
run ("notepad.exe " & "k:sdtemptest.txt")
; #FUNCTION# ======================================================================================
; Name ................:    _stringsplit2d($str,$del)
; Description .........:    create 2d array where each row is a @lf delimited text string comprised
;                          of columns delimited by a user defined string
; Syntax ..............:    StringSplitW($str, $del)
; Parameters ..........:    $str - string to split
;                          $del - the delimter for columns
; =================================================================================================
func _stringsplit2d($str,$del)
 local $a1 = stringsplit($str,@lf,1), $a2
 local $rows = ubound($a1),$cols = 0
 ; determine max number of columns by splitting each row and keeping highest ubound value
 for $i = 0 to ubound($a1) - 1
  $a2 = stringsplit($a1[$i],$del,1)
  if ubound($a2) > $cols then $cols = ubound($a2)
 next
 ; define and populate array
 local $o[$rows][$cols]
 for $i = 1 to $rows - 1
  $a2 = stringsplit($a1[$i],$del,1)
  for $j = 0 to ubound($a2) - 1
   $o[$i][$j] = $a2[$j]
  Next
 next
 return $o
endfunc
; #FUNCTION# ======================================================================================
; Name ................:    _print2d_array
; Description .........:    create a formatted text file from delimited string input
; Syntax ..............:    _print2d_array($str, $del, $output_file_name)
; Parameters ..........:    $str - string to split
;                          $del - the delimter for columns
;                          $output_file_name - fully qualified output file name
; =================================================================================================
Func _print2d_array($str,$del,$output_file_name)
 $str = stringregexpreplace($str,@crlf,@lf)
 Local $a10 = StringSplit($str,@lf,3), $numcols = 0, $a20, $matrix = ""
 ; find max number of columns
 For $i = 0 To UBound($a10) - 1
  $a20 = StringSplit($a10[$i],$del)
  if ubound($a20) > $numcols then $numcols = ubound($a20)
 Next
 ; find max size of each column
 local $colsize[$numcols]
 For $i = 0 To UBound($a10) - 1
  $a20 = StringSplit($a10[$i],$del)
  For $j = 0 To $a20[0]
   If StringLen($a20[$j]) > $colsize[$j] Then $colsize[$j] = StringLen($a20[$j]) + 5
  Next
 Next
 ; now format the output line
 For $i = 0 To UBound($a10) - 1
  $a20 = StringSplit($a10[$i],$del)
  For $j = 0 To $a20[0]
   $matrix &= StringFormat("%-" & $colsize[$j] & "s",$a20[$j]) & "|"
  Next
  $matrix &= @CRLF
 next
 ; and finally write the output file
 local $hfl = FileOpen($output_file_name,2)
 FileWrite($hfl,$matrix)
 FileClose($hfl)
 $hfl = 0
endfunc

kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

Thanks for the tips. Perhaps I was not clear in my need. I am looking for a BASIC-LIKE tab function that would do this, per below in conjunction with the FileWrite or FileWriteLine command. Any suggestions? Thanks.

BASIC- TAB function (part of the BASIC Keyword Index)

Syntax:

TAB(n)

Effect:

This function causes the print position to move to the nth column.

Comments:

If the current print position is already beyond n, then the print position will move to the nth column on the next line. If n is greater than the output width, the print position is moved to n MOD WIDTH. If n is less than one, the print position will become 1. TAB may only be used in PRINT and LPRINT statements.

Example:

'80 column screen

PRINT TAB(-10) "minus ten"

PRINT TAB(175) "one-hundred-and-seventy-five"

PRINT TAB(1) "ten"

Link to comment
Share on other sites

There's nothing that would correspond to that functionality available natively in AutoIt. There may be a function or code snippet that someone has come out with, but nothing that I have run across yet. I haven't seen anyone use that function since dot matrix printers went out of style. :)

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

SamG,

The

stringformat
function can be used to produce formatted output as follows
#include <array.au3>

; create some test data
local $a10[10][5], $output_file_name = 'k:sdtempformat_test.txt'
for $i = 0 to ubound($a10,1) - 1
$a10[$i][0] = 'line ' & $i
for $j = 1 to ubound($a10,2) - 1
$a10[$i][$j] = 'col ' & $j
Next
next
; use stringformat to output formatted columns 30 spaces wide
local $out
for $i = 0 to ubound($a10,1) - 1
for $j = 0 to ubound($a10,2) - 1
$out &= stringformat('%-30s',$a10[$i][$j]) ; <<<<<< this is the function that is similar to TAB...see the help file
Next
$out &= @LF
Next
local $file = fileopen($output_file_name,2)
if $file = -1 then
msgbox(0,'Error','File open for output in erase mode failed for file = ' & $file)
Exit
endif
filewrite($file,$out)
fileclose($file)
shellexecute($output_file_name)

In this case I am using an array for the data. You can use any variable/string, see the help file.

To run this just change the output file name.

Good Luck,

kylomas

edit:code correction

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

SamG,

Another, simpler example. There is one format control for each variable. See the help file.

local $name1 = 'john smith', $dep1 = 'accounting', $salary1 = 'gazillions', $boss1 = 'mickey mouse'
consolewrite('!> ' & stringformat('%-20s%-20s%-20s%-20s',$name1, $dep1, $salary1, $boss1) & @lf)

kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

kylomas,

The example in #8 I would use @ScriptDir & 'format_test.txt' instead of the absolute path. Not all have a K: drive.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...