Summary of methods for operating tables with python

1. Create a table, create a worksheet

Use xlwt library

wb=xlwt.Workbook()

ws=wb.add_sheet("News Summary 1")

wb.save('./News summary.xls')

2. Open the table, open the worksheet

Use openpyxl library

method 1:

filename ='News summary.xlsx'

wb = load_workbook(filename)

ws = wb.activewb.save(filename)

Method 2:

filename ='News summary.xlsx'

wb1 = load_workbook(filename)#Open workbook

ws = wb1['Sheet1']#Open the worksheet

3. Enter content in the cell

Use xlwt library

ws.write(0,0,"Serial Number")

ws.write(0,1,"5G News")

ws.write(0,2,"5G news link")

4. Adjust the cell format (font format, row height, column width, centering)

Use openpyxl library

Formatting of the table font:

bold_itatic_24_font = Font(name=‘宋体’, size=14, italic=False, color=colors.BLACK, bold=True)

#Table header font format

ws[‘A1’].font = bold_itatic_24_font

ws[‘B1’].font = bold_itatic_24_font

ws[‘C1’].font = bold_itatic_24_font

Center setting of table font:

ws[A1].alignment = Alignment(horizontal=‘center’, vertical=‘center’)

Table row height setting:

ws.row_dimensions[1].height = 30

Table column width settings:

ws.column_dimensions[‘B’].width = 70

ws.column_dimensions[‘C’].width = 80

5. Delete rows or columns

Use openpyxl library

Delete column

ws.delete_cols(1,1)#Delete the first column

ws.delete_cols(4, 1)#Delete the third column

Delete row

ws.delete_rows(1,1)#Delete the first row

6. Delete duplicates in the table

Use pandas library

#Read the data in Sheet1 in Excel

t = pandas.read_excel('News summary.xls','News summary 1')

data = pandas.DataFrame(t)

#Identify duplicate news, and delete duplicate news

re_row = data.drop_duplicates(['5G News Link'])

re_row.to_excel("News summary.xlsx")#Create a new news summary file

os.remove('./新闻集.xls')#Delete the original news summary file

Guess you like

Origin blog.csdn.net/qq_42967630/article/details/90761698