1

Pythonを使用してExcelスプレッドシートから読み書きするために、pythonパッケージxlrdおよびxlwtを使用しています。ただし、問題を解決するためのコードの書き方がわかりません。

最初のスプレッドシートに、州名が 2 文字の略語とフルネーム (一部はすべて小文字、一部は最初の文字が大文字) の列があります。最初のシートの名前を読み取り、2 番目のシートの名前と一致するかどうかを確認し、2 番目のシートにある州の略語として 3 番目のシートに書き込む別のシートを作成しようとしています。これは理にかなっていますか?

とにかく、50 の個別の「for」ループを作成しないと、その方法がわかりません。これが私がこれまでに持っているものですが、実行すると最初の列が空白になりました。

import xlrd #reads
import xlwt #writes

input_book = xlrd.open_workbook("file_path_here")
input_sheet = input_book.sheet_by_index(0)
state_book = xlrd.open_workbook("file_path2_here")
state_sheet = state_book.sheet_by_index(0)
output_book = xlwt.Workbook()
output_sheet = output_book.add_sheet('test')

for row in range(input_sheet.nrows):
    state = input_sheet.cell_value(row, colx=1) #state names are in col 1
    Value1 =input_sheet.cell_value(row, colx=2) #data being left unchanged, just copied to output sheet
    Value2 =input_sheet.cell_value(row, colx=3)
    Value3 =input_sheet.cell_value(row, colx=4)
    for name in range(state_sheet.nrows):  #a sheet with state names in col 0, state abrevs in col 1
        state_name = state_sheet.cell_value(name,colx=0)
        state_abrev = state_sheet.cell_value(name, colx=1)
        if state.lower() == state_name:
            output_sheet.write(row,0,state_abrev)
    output_sheet.write(row,1,Value1)
    output_sheet.write(row,2,Value2)
    output_sheet.write(row,3,Value3)

print ('done')
output_book.save('output.xls')
4

1 に答える 1