pythonexcelopenpyxl

openpyxl - how to put value with a leading single quote


In Excel, single quote prefix is used to designate that value is a text and should not be converted to any other type. Normally, single quote is not displayed when viewing a workbook (but it is visible when editing cell content).

Is it possible to put such value in a cell, using openpyxl? I have found no way to do it.

Here is sample code

import openpyxl
import os
wb = openpyxl.Workbook()
sheet = wb.get_active_sheet()
sheet.cell("A1", value="'value")
sheet.cell("B1").value = "'value"
sheet.cell("C1").set_explicit_value("'value", 's')
outpath = r"d:\dmishin\temp\wb.xlsx" #put your path here
wb.save(outpath)
os.startfile(outpath)

This code creates a worksheet with 3 cells, putting 'value to them. I expect to see the text without leading quote when viewing it, but instead I see this:

Visible leading quote

Manual editing creates this (note that quote is still displayed when editing)

No leading quote visible

After comparing XLSX files contents manually, I have an impression that the information about the quote is stored in the cell style tag, quotePrefix attribute.

In openpyxl sources, CellStyle class has corresponding boolean field quotePrefix. However, I see no way to manually set this field. Is it possible?


Solution

  • You're not allowed to change quotePrefix attribute on a cell, but if you really need to have quotePrefix set to True, you can update the cell's _style attribute which has a style_array (https://openpyxl.readthedocs.io/en/stable/api/openpyxl.styles.cell_style.html#openpyxl.styles.cell_style.StyleArray) array('i', [0, 0, 0, 0, 0, 0, 0, 0, 0]) so that the 8th value (which should correspond to quotePrefix) is 1.