Python programming quick start 12.4, 12.7-12.10 project: spreadsheet operation

1. Reading data from the spreadsheet
The raw data can be downloaded from http://nostarch.com/automatestuff/. On this site, you can download the code and data packages in the book "Python Programming Quick Start-Automating Trivial Work" for easy practice.
Refer to the following code:

import openpyxl, pprint
wb = openpyxl.load_workbook('c:\censuspopdata.xlsx')
sheet = wb['Population by Census Tract']

txtfile = open('c:\dell\jieg.txt', 'w', encoding='utf-8')
neir = '县名'.ljust(25) + '户口区数量'.ljust(15) + '人口数量'.ljust(25) + '\n'
txtfile.write(neir)

rows = sheet.max_row  #取得最大行数,与原书不同
cols = sheet.max_column  #取得最大列数,与原书不同
print(rows,cols)
county = []
for i in range(2, rows + 1) :  #从第二行(EXCEL表中第一行是列标头)开始取值一直取到最后一行。range()函数不包含rows本身,因此要加1
    dqname = sheet.cell(row = i, column = 3).value  #取得当前表第三列的即县的名称
    county.append(dqname)

counset = set(county) #利用集合的去重功能去重

coundic = {
    
    }

print('正在统计数据...')

for hk in counset :  #遍历所有县名
    hkq = 0
    pop = 0
    for ccell in range(2, rows + 1) :   # 遍历所有行
        if sheet.cell(row = ccell, column = 3).value == hk :  #判断当前行的县名跟正在遍历有县名相符时
            hkq += 1
            pop += sheet.cell(row = ccell, column = 4).value
    coundic.setdefault(hk,[hkq,pop])

    neir = hk.ljust(25) + str(hkq).rjust(15) + str(pop).rjust(25)
    txtfile.write(neir)
    txtfile.write('\n')
neir = '县数:'+str(len(counset))+';户口区数量:'+str(hkq)+';人口数量:'+str(pop)
txtfile.close()
print('统计完成,输出数据...')
pprint.pprint(coundic)
print('输出完成')

Tested without error.

2. Spreadsheet format setting
Due to the version upgrade of openpyxl, the actual operation code is different from the book, see notes for details.

import openpyxl,os
from openpyxl.styles import Font

wb = openpyxl.Workbook()
sheet = wb['Sheet']  #与原书不同
sheet['A1'] = '测试'
fontobj = Font(name='宋体',size=24,bold=True,italic=True)  #与原书不同
sheet['A1'].font = fontobj  #与原书不同

sheet['B2'] = 200
sheet['B3'] = 300
sheet['B4'] = '=B2+B3'

sheet.row_dimensions[1].height = 50
sheet.column_dimensions['B'].width = 20
sheet.column_dimensions['A'].width = 50
sheet.merge_cells('A1:A3')
sheet.merge_cells('B5:B6')
sheet.unmerge_cells('B5:B6')

wb.save(r'c:\python\test.xlsx')  #与原书不同
wb.close()

Guess you like

Origin blog.csdn.net/any1where/article/details/128432321