1

I'm new in python, and I tried to write data into existing excel file using openpyxl, my excel file has a little complicated format. After running my simple code, I checked my excel file and all the format is corrupted.

This is my code:

import openpyxl

xfile = openpyxl.load_workbook('sample.xlsx')
sheet = xfile.get_sheet_by_name('Sheet1')
sheet['A1'] = 'hello world'

xfile.save('sample.xlsx')

Please help me figure out how to fix it, or suggest an alternative library that can work well with "xlsx" file.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Son_Nguyen
  • 73
  • 1
  • 1
  • 9
  • 1
    Can you give us more info on what format your file has, and what precisely isn't working?. In order to have a minimal, complete, and verifiable example you should clarify what you mean by "all format have crashed". – bpachev Aug 01 '16 at 18:01
  • @bpachev my excel file has some format like "font, color, background color, border, merge cell, align, valign, formular, data validation", when i wrote data into it, "border, border color" have lost. I wrote into one sheet, and every sheet have same affect. – Son_Nguyen Aug 02 '16 at 03:51
  • Thanks for the clarification. I'd be great if you could post a sample file where this happens, and then I can reproduce and fix the problem. – bpachev Aug 02 '16 at 03:57
  • @bpachev Sorry i didn't reply you sooner, that file belong to my company, so i can send it out of my company, i really appreciate your help. I think i need find another library can work with .xlsx file. – Son_Nguyen Aug 02 '16 at 06:32
  • That, or update openpyxl. See this question: http://stackoverflow.com/questions/6772438/use-openpyxl-to-edit-a-excel2007-file-xlsx-without-changing-its-own-styles – bpachev Aug 02 '16 at 13:20
  • @bpachev, oh, i already have installed the latest version of openpyxl. – Son_Nguyen Aug 03 '16 at 03:07
  • The linked question is basically the same as yours. If you're on Windows, you can talk to excel using pywin32. The tutorial (in that answer) is here: http://pythonexcels.com/python-excel-mini-cookbook/ Let me know if this works. – bpachev Aug 03 '16 at 03:29
  • Thanks @bpachev, i think i will try pywin32. – Son_Nguyen Aug 03 '16 at 07:06

0 Answers0