How to extract first two characters of a string in openpyxl Python?

Question:

I am trying to assign cell value in python openpxl by referencing the first 2nd characters of a string in another cell eg say the content of cell "A2" is the string "Random", I am trying to extract the first two characters Ra

The codes I tried so far:

import openpyxl
from openpyxl import Workbook, load_workbook

wb = openpyxl.load_workbook('c:/Users/me/myfolder/myfile.xlsx')
ws = wb["mysheet"]

ws["A4"] = ws["A3":2]

I also tried

ws[A4]= ws["A3"]:2

I have also been desperate enough to try

ws["A4"] = LEFT(sheet["A3"],2)

None works

Asked By: ohmandy

||

Answers:

You have to use the cell.value property to return a string and after that, you can slice it.

Try this :

ws["A4"].value = ws["A3"].value[:2]
Answered By: abokey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.