Installation module
1. Find the corresponding module http://www.python-excel.org/
2. Install with pip install
pip install xlrd
pip install XlsxWriter
pip list view
XlsxWriter example
1 import xlsxwriter 2 3 # Create a workbook and add a worksheet 4 workbook = xlsxwriter.Workbook("demo.xlsx") 5 worksheet = workbook.add_worksheet() 6 7 # Set column width 8 worksheet.set_column("A:A", 20) 9 10 # Set format 11 bold = workbook.add_format({"bold": True}) 12 13 # Set cell value 14 worksheet.write("A1", "Hello") 15 16 # Formatted cells 17 worksheet.write("A2", "World") 18 19 # Write some numbers and identify them with rows and columns 20 worksheet.write(2, 0, 123) 21 worksheet.write(3, 0, 123.456, bold) 22 23 # Insert a picture 24 worksheet.insert_image("B5", "C:/Users/Cheng/Desktop/1.png") 25 26 # Close file stream 27 workbook.close()
The operation results are as follows:
Merge Excel data
thinking
Excel is composed of rows and columns, so here we read all the data in all the sheet s in all the files to form a two-dimensional array, and then write the new excel
Code
1 import xlrd 2 import xlsxwriter 3 4 source_xls = ["D:/python/1.xlsx", "D:/python/2.xlsx"] 5 target_xls = "D:/python/3.xlsx" 6 7 # Read data 8 data = [] 9 for i in source_xls: 10 wb = xlrd.open_workbook(i) 11 for sheet in wb.sheets(): 12 for rownum in range(sheet.nrows): 13 data.append(sheet.row_values(rownum)) 14 print(data) 15 # Write data 16 workbook = xlsxwriter.Workbook(target_xls) 17 worksheet = workbook.add_worksheet() 18 font = workbook.add_format({"font_size":14}) 19 for i in range(len(data)): 20 for j in range(len(data[i])): 21 worksheet.write(i, j, data[i][j], font) 22 # Close file stream 23 workbook.close()
Operation result
Experience
At the beginning of learning Python, maybe it's because I'm used to Java code. At the beginning of learning, I feel that the syntax is strange. It's similar to Java, and it's similar to JavaScript and Perl...
It deserves to be an object-oriented, interpretive high-level programming language!!!