Excel formatted cells (testing needed) Topic is solved

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
mcl
Posts: 359
Joined: 04 May 2018, 16:35

Excel formatted cells (testing needed)

05 Apr 2023, 19:30

I was working on a script that puts formatted text in Excel, but that required too much COM calls.

Then I found out that Excel understands copied HTML pretty well.
That required some DllCalls or GPT magic to put HTML format into clipboard, but still was way faster.

Then I found out that I don't need that special clipboard format, I can use regular text structured like that format.

This seems to work with my olde Excel 2007.
Can anyone confirm if it works in older/newer versions? Screenshot of expected result is attached.

Code: Select all

#Requires AutoHotkey v2.0

ExcelHtmlToClip( htmlText, styleText := '' ) {
	htmlTextBefore := '<html><head><style>' . styleText . '</style></head><body><table><!--StartFragment-->`r`n'
	htmlTextAfter  := '`r`n<!--EndFragment--></table></body></html>'
	
	; Text will be interpreted as UTF-8. Minus one for zero-terminator
	strLenBefore := StrPut(htmlTextBefore, 'UTF-8') - 1
	strLenUser   := StrPut(htmlText , 'UTF-8') - 1
	strLenAfter  := StrPut(htmlTextAfter, 'UTF-8') - 1
	
	; Offsets of text chunks. First (header) is 105 characters including newlines
	ptr1 := 105
	ptr2 := ptr1 + strLenBefore
	ptr3 := ptr2 + strLenUser
	ptr4 := ptr3 + strLenAfter
	
	header := Format(
		  'Version:1.0`r`n'
		. 'StartHTML:{1:010d}`r`n'
		. 'EndHTML:{2:010d}`r`n'
		. 'StartFragment:{3:010d}`r`n'
		. 'EndFragment:{4:010d}`r`n'
		
		, ptr1, ptr2, ptr3, ptr4
	)
	
	A_Clipboard := header . htmlTextBefore . htmlText . htmlTextAfter
}


defaultXlStyles := '
(
	br { mso-data-placement: same-cell; }
	td {
		font-size: 11.0pt;
		font-family: Calibri, sans-serif;
		mso-number-format: '"\@"';
		white-space:nowrap;
	}
)'

myStyles := defaultXlStyles . '
(
.red  {font-weight: bold; color: red; font-style: italic;}
.redcell  {color: red; background: #FFF0F0; border-bottom: 2pt solid #FF0000;}
)'

myHtml := '
(
<tr><td colspan=2>Γεια <font class=red>σου κόσμο</font>!</td></tr>
<tr><td class=redcell style="white-space:normal">Red<br/>cell</td></tr>
)'

Loop 100 {
	r := 255 - Random(0, 32)
	g := 255 - Random(0, 32)
	b := 255 - Random(0, 32)
	
	myHtml .= Format('<tr><td style="background-color:#{1:06x}">', (r<<16)|(g<<8)|(b<<0))
	. "It'sa me, line <b>#" . A_Index . "</b></td></tr>"
}

ExcelHtmlToClip(myHtml, myStyles)
Msgbox('Now try pasting that in Excel!')
Attachments
excelhtml.png
excelhtml.png (10.73 KiB) Viewed 239 times
github://oGDIp - GDI+ wrapper for AHK v1.1
swagfag
Posts: 6222
Joined: 11 Jan 2017, 17:59

Re: Excel formatted cells (testing needed)  Topic is solved

05 Apr 2023, 20:03

its working in Excel 365 Version 2208 Build 16.0.15601.20540

Return to “Ask for Help (v2)”

Who is online

Users browsing this forum: No registered users and 31 guests