Python writes an existing instance of Excel data

Source: Internet
Author: User
Tags xsl file
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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.