Below for you to share a python write to the existing instance of Excel data, has a good reference value, I hope to be helpful to everyone. Come and see it together.
Python can use XLRD to read Excel, use XLWT to write Excel, but if you want to write data to an existing Excel, you need another library xlutils to work with.
Approximate idea:
1. Open an existing XSL file with Xlrd.open_workbook
Note Adding the parameter formatting_info=true to save the format of the previous data
2, then use, from xlutils.copy import copy, and then copy to from the open xlrd book variable, copied a copy, become the new XLWT workbook variable
3, then for the XLWT of the workbook variable, is normal:
By Get_sheet to get the corresponding sheet, get the sheet variable, you can go to sheet, write new data
4, after writing the new data, the final save saves
Source code Example:
Import xlrdimport osfrom xlutils.copy import copyfrom XLWT import styledef writeexcel (row, col, str, styl=style.default_st YLE): RB = Xlrd.open_workbook (file, formatting_info=true) WB = Copy (RB) WS = Wb.get_sheet (0) ws.write (row, col, str, styl) Wb.save (file) style = Xlwt.easyxf (' Font:height, Color-index red, bold on;align:wrap on, vert Centre, Horiz Center '); w Riteexcel (1, 1, ' Hello World ', style)
If you need excel in the original format, you need to add parameters
Formatting_info=true
If you need to add an Excel style, pass the style string to XLWT.EASYXF
Merge cells:
Ws.write_merge (Top_row, Bottom_row, Left_column, Right_column, String)