读取和写入文件中的特定单元格

时间:2018-10-24 23:04:05

标签: python pandas numpy

我正在编写一个程序,从excel表中读取该程序,它随机选择一行(100行,2列)。

with open("file1.csv") as f:
     reader = csv.reader(f)
     for index, row in enumerate(reader):
         if index == 0:
            chosen_row = row
         else:
            r = random.randint(0, index)
            if r == 0:
                chosen_row = row

我希望它写入特定的行/列。 例如;如果它是从第4行第A列中随机选择的话,则会将答案写入第4行第B列。

这就是我所拥有的(这是错误的,它不会写入特定的单元格)

    x = input(chosen_row[0])
    srcfile = openpyxl.load_workbook("file1.csv",read_only=False, 
    keep_vba= True)
    sheetname = srcfile.get_sheet_by_name('Sheet1')
    sheetname.cell(row=chosen_index,column=2).value = x 
    srcfile.save('file1.csv')

我想知道它如何随机选择一行,并让我的代码获取用户的输入并将其写入该行的特定单元格中。

1 个答案:

答案 0 :(得分:0)

来自openpyxl上的示例代码:

from openpyxl import Workbook
wb = Workbook()

# grab the active worksheet
ws = wb.active

# Data can be assigned directly to cells
ws['A1'] = 42

鉴于此,您应该能够使用

查看分配给定单元格的值
ws['A1']

并随机分配其他:

ws['A1']=ws[random[row]+random[cell]]

ramdom [row / cell]是伪代码。您将选择要如何定义随机[行/单元格]数据。

别忘了保存,顺便说一句。

# Save the file
wb.save("sample.xlsx")
相关问题