In MS Excel, Text Width of text in a cell returned by GetTextExtentPoint32W is more than the actual width - python-2.7

I'm using GetTextExtentPoint32W to get width of a text in a cell in MS Excel 2010. The cell width is fetched using ActiveCell.Width. These two widths are then compared to determine whether the text fits in the cell or extends out of the cell.
Visually, even though the text fits perfectly in the cell, the text width returned by the method is more than the cell width. Also, when I increase the font size the difference between actual text width and that returned by the method increases.
Following is a part of the source code used to achieve the result. Please help me solve this error.
hDC = ctypes.windll.user32.GetDC(self.windowHandle)
tempBMP = ctypes.windll.gdi32.CreateCompatibleBitmap(hDC, 1, 1)
hBMP = ctypes.windll.gdi32.SelectObject(hDC, tempBMP)
iFontSize = self.excelCellObject.Font.Size
deviceCaps = ctypes.windll.gdi32.GetDeviceCaps(hDC, 90)
iFontSize = int(iFontSize)
iFontSize = ctypes.c_int(iFontSize)
iFontSize = ctypes.windll.kernel32.MulDiv(iFontSize, deviceCaps, 72)
iFontSize = iFontSize * -1
iFontWeight = 700 if self.excelCellObject.Font.Bold else 400
sFontName = self.excelCellObject.Font.Name
sFontItalic = self.excelCellObject.Font.Italic
sFontUnderline = True if self.excelCellObject.Font.Underline else False
sFontStrikeThrough = self.excelCellObject.Font.Strikethrough
#Create a font object with the correct size, weight and style
hFont = ctypes.windll.gdi32.CreateFontW(iFontSize,
0, 0, 0,
iFontWeight,
sFontItalic,
sFontUnderline,
sFontStrikeThrough,
False, False, False,
False, False,
sFontName)
#Load the font into the device context, storing the original font object
hOldFont = ctypes.windll.gdi32.SelectObject(hDC, hFont)
sText = self.excelCellObject.Text
log.io("\nText \t"+sText+"\n")
textLength = len(sText)
class structText(ctypes.Structure):
_fields_ = [("width", ctypes.c_int),
("height",ctypes.c_int)]
StructText = structText()
getTextExtentPoint = ctypes.windll.gdi32.GetTextExtentPoint32W
getTextExtentPoint.argtypes = [ctypes.c_void_p,
ctypes.c_char_p,
ctypes.c_int,
ctypes.POINTER(structText)]
getTextExtentPoint.restype = ctypes.c_int
#Get the text dimensions
a = ctypes.windll.gdi32.GetTextExtentPoint32W(hDC,
sText,
textLength,
ctypes.byref(StructText))
#Delete the font object we created
a = ctypes.windll.gdi32.DeleteObject(hFont)
a = ctypes.windll.gdi32.DeleteObject(tempBMP)
#Release the device context
a = ctypes.windll.user32.ReleaseDC(self.windowHandle, hDC)
textWidth = StructText.width
cellWidth = self.excelCellObject.Width
Thanks.

I do not use Python or Excel 2010 so cannot comment on your current approach. However, I have struggled with a similar problem. I hope the following points will be helpful.
Background
If you hover over the right boundary of an Excel column and hold the left mouse button you will get a display of the format: “Width: n.nn (mm pixels)”.
The help for the ColumnWidth property says:
One unit of column width is equal to the width of one character in the
Normal style. For proportional fonts, the width of the character 0
(zero) is used.
Use the Width property to return the width of a column in points.
As far as I can tell, “Normal style” means the standard font name and size at the time the workbook was created. Changing the standard font name and size for an existing workbook does not appear to have any effect. Changing the font name and size for a worksheet has no effect.
Two example displays for a standard width column are:
For Arial 10 Width: 8.43 (64 pixels)
For Tahoma 10.5 Width: 8.38 (72 pixels)
I have created a string of zeros and attempted to measure how many are visible depending on the width of the column. I found the number of zeroes that I could see matched the value displayed reasonably well for such as subjective measure.
With VBA, the ColumnWidth property of a column or cell sets or returns the width in characters.
With VBA, The read only Width property of a column or cell returns .75 * the width in pixels.
The significance of the above information is that the width values obtained from Excel are not necessarily correct for the font being used.
My problem and the solution I discovered
The problem I had was that I was merging cells and filling them with text. Although Excel will adjust the height of a row so the text within an unmerged cell is visible, it will not do so for a merged cell. I tried many techniques including Microsoft’s .Net, text rendering routines without success. Nothing I tried would reliably emulate Excel’s system for determining the width of text.
The technique I eventually used successfully involved picking a cell to the right and below all used cells for experimental use. I adjusted the width of the experimental cell’s column to match the combined width of the merged cell and copied the formatted value from the cell whose height I wanted. Because the experimental cell was unmerged, Excel would adjust the height as appropriate. I then made sure the source row was at least this height.
The key feature of this technique was that I was not trying to emulate Excel’s system for determining the width of text; I was using Excel’s system.
You would need to try different column widths for the experimental cell. I would start with the current width of the source column. If the row height matches that for a single row, the width of the source column is already sufficient. If the row height is more than that for a single row, I would increase the column width until the row height matched that for a single row and then adjust the source column’s width to match. If you start with the widest value (in characters or Python’s text width) you will probably get the source column width correct at the first attempt which would avoid the need for later adjustments.

Related

Change rowheight of Apex Interactive grid

In my application I need to set the rows to show the text area columns in more than one line (say 3 lines). However I don't want the text area column contents in one single line, despite the row height is increased. It should be wrapped to the number of lines.
If I turnoff fixed rowheight attribute. Then each row has a different height. Thats not what I'm expecting
I tried below inline css, but it is not changing
#static_id .a-GV-cell {<br/> height: 80px;<br/>}<br/>.wrap-cell {<br/> max-height: 64px;<br/> white-space: normal;<br/> overflow: hidden;<br/>
However this still only shows the text area column contents in one single line, despite the row height is increased.
thanks in advance

Python-docx - How to change table font size?

table = document.add_table(rows=1, cols=1)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
I have to change font size of text 'Qty' in table with one row and one column, how can I make it?
You need to get the paragraph in the cell. From the documentation of python-docx:
3.5.2 _Cell objects:
class docx.table._Cell (tc, parent)
paragraphs
List of paragraphs in the cell. A table cell is required to
contain at least one block-level element and end with a paragraph. By
default, a new cell contains a single paragraph. Read-only
Reference: python-docx Documentation - Read the Docs
The code:
To change font size of text 'Qty'
paragraph =hdr_cells[0].paragraphs[0]
run = paragraph.runs
font = run[0].font
font.size= Pt(30) # font size = 30
To change font size of the whole table:
for row in table.rows:
for cell in row.cells:
paragraphs = cell.paragraphs
for paragraph in paragraphs:
for run in paragraph.runs:
font = run.font
font.size= Pt(30)
Reference of how to access paragraphs in a table: Extracting data from tables
Up there the solution really helped. I use it for a while. But I found a tiny problem:time. As your table grows bigger the time you cost to build the table getting longer. So I improve it. Cut two rounds. Here you are:
The code changes the whole table
for row in table.rows:
for cell in row.cells:
paragraphs = cell.paragraphs
paragraph = paragraphs[0]
run_obj = paragraph.runs
run = run_obj[0]
font = run.font
font.size = Pt(30)
When you cut two rounds you save the time
Building on user7609283 answer, here is a short version to set a cell to bold (the cell must contain text before applying format as it looks for the first paragraph):
row_cells = table.add_row().cells
row_cells[0].text = "Customer"
row_cells[0].paragraphs[0].runs[0].font.bold = True
This font change applies to all cells of a table and is streamlined. All cells must contain text before being formatted or an index out of range error is thrown:
for row in table.rows:
for cell in row.cells:
cp = cell.paragraphs[0].runs
cp[0].font.size = Pt(14)
This next font change applies to a single cell as wanted, in this case the top left cell:
tc = table.cell(0, 0).paragraphs[0].runs
tc[0].font.size = Pt(14)

Format a text on cell in two color in Coldfusion

Using Coldfusion 10, I need to format a cell contents in two color(Black and Blue). Let a cell on spreadsheet contains a string "Text1: Text2". where color of "Text1" should be black and "Text2" should be blue.
I have tried below code, but it produces all blue text.
SpreadsheetAddRow(spreadsheetData,"Text1: Text2",1,1);
format1=StructNew();
format1.color="black";
SpreadsheetFormatRow(spreadsheetData,format1,1);
format1.color="blue";
SpreadsheetFormatRow(spreadsheetData,format1,1);
How I can apply two color to format single cell ?
It is not supported with the built in functions. However, you can tap into the underlying POI library and use a RichTextString to accomplish this.
Assuming you have already created the worksheet and an empty cell:
spreadsheetData = SpreadSheetNew("Sheet1", true);
SpreadsheetAddRow(spreadsheetData,"",1,1);
Grab reference to the underlying Workbook and create fonts with the appropriate colors:
wb = spreadsheetData.getWorkbook();
Colors = createObject("java", "org.apache.poi.ss.usermodel.IndexedColors");
greenFont = wb.createFont();
greenFont.setColor(Colors.GREEN.index);
blueFont = wb.createFont();
blueFont.setColor(Colors.BLUE.index);
Then create a RichTextString object and append each part of the text with the desired color:
// Using GREEN and BLUE for demo purposes
richString = createObject("java", "org.apache.poi.xssf.usermodel.XSSFRichTextString").init();
richString.append("Text1: ", greenFont);
richString.append("Text2", blueFont);
Finally, apply the RichTextString to the empty cell, ie A1 you created earlier. Note, unlike in CF, the indexes are 0-based.
cell = wb.getSheet("Sheet1").getRow( 0 ).getCell( 0 );
cell.setCellValue(richString);

limit the Y-axis character in google visulaization combo graph to given limit

Hi,
Is there any way to limit the Y-axis character in google visulaization combo graph to given limit and then ...
By Default it is doing when more then 22 character. But I want to reduce it to given character.
Attached is the screen shot
I assume you meant X-axis, not Y-axis, given your screen shot. There is a quick-and-dirty approach that truncates the displayed strings to 22 characters, but this will affect the tooltips as well as the axis labels:
for (var i = 0; i < data.getNumberOfRows(); i++) {
// assumes column 0 is your labels
var label = data.getValue(i, 0);
label = label.substring(0, 22);
data.setFormattedValue(i, 0, label);
}
If you just want to affect the axis labels, there are different approaches you can take, and which one you take depends on what you want to achieve by truncating the labels. What is it that you want to achieve?

QAxObject Excel sheet -- set default font for entire Excel sheet

I am able to set the size & font of a single cell.
QAxObject *range = excelSheet->querySubObject("Cells(int,int)", row, col);
range = range->querySubObject("Font");
range->setProperty("Size", 10);
range->setProperty("Name", "Arial");
How can i change the FONT default size & type of full excel sheet ?
See http://dynamicsuser.net/forums/p/10304/52610.aspx, you have to select all the cells in the sheet (as a range), and then select the font for them. Try to adapt the following VB code:
xlsRange := xlsWorksheet.Cells;
xlsRange.Font.Name := 'Zapf Dingbats';