將Excel中的漢字列,轉換成拼音首字母,並保存
需要安裝導入 pypinyin、openpyxl 庫
# pip install pypinyin from pypinyin import lazy_pinyin, Style import openpyxl def py(str_data): """ 獲取字符串的首字母 :param str_data: 字符串 :return: 返回首字母縮寫(大寫) """ p = ''.join(lazy_pinyin(str_data, style=Style.FIRST_LETTER)) return p.upper() # return 首字母縮寫[:-4].upper() # 不要倒數後四位,去掉有限公司 def read_excel(): file = "D:\\Temp\\Test.xlsx" # 打開excel excel = openpyxl.load_workbook(file) # 使用指定工作表 # sheet = excel.active # 當前激活的工作表 sheet = excel.get_sheet_by_name('Sheet1') # 讀取標題行 for row in sheet.iter_rows(max_row=1): title_row = [cell.value for cell in row] print(title_row) # 讀取指定列的數據 將第5列的漢字轉成拼音後,存放到第6列中 for col in sheet.iter_cols(min_row=1, min_col=5, max_row=None, max_col=5): col_value = [row.value for row in col] for idx, cv in enumerate(col): if str(cv.value) == 'None': # 跳過空值 continue sheet.cell(row=idx + 1, column=6, value=py(cv.value)) print('%s %s %s' % (idx, cv.value, str(cv.value) == 'None')) excel.save(file) excel.close() print(col_value) if __name__ == "__main__": read_excel() # print(py("WPF 在類型爲 的對象上找不到 command 屬性")) print('done')