以下代码可以直接运行
import openpyxl
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
from openpyxl.utils import get_column_letter, column_index_from_string
# 向sheetobj中的columnname列从start_row开始写入listdata
def insert_listdata_to_column(sheetobj,listdata,column_name,start_row=2):
colindex = column_index_from_string(column_name)
for rowindex in range(start_row, start_row + len(data)):
val = data[rowindex - start_row]
try:
sheet.cell(row = rowindex,column = colindex,value = val)
except:
val = ILLEGAL_CHARACTERS_RE.sub(r'',val)
sheet.cell(row = rowindex,column = colindex,value = val)
column_mapping = {
"A":[1,2,3,4,5],
"b":["aa","bb","cc","dd","ee"]
}
#向已经存在的表格写入
wb = openpyxl.load_workbook(dest_file)
sheet = wb["sheetname"]
for key,val in column_mapping.items():
col_name = key
data = val
insert_listdata_to_column(sheet,data,col_name,2)
wb.save(dest_file)
#创建新的表格
wb = openpyxl.Workbook()
sheet = wb.active
for key,val in column_mapping.items():
col_name = key
data = val
insert_listdata_to_column(sheet,data,col_name,5)
wb.save("ttt.xlsx")