![](/img/trans.png)
[英]How do you lookup a particular pandas dataframe column value in a reference table and copy a reference table value to the dataframe?
[英]How do you use Pandas to copy a cell value into a table in Word?
因此,我試圖將 Excel 文件中的單元格值復制到 Word 文檔中的表格中,但是,在將表格單元格與 Excel 文件中的單元格值等同時,我不斷收到錯誤消息。 我已經嘗試了幾件事,但一直出現錯誤
嘗試 1:
from docx import Document
from docx.shared import Pt
from openpyxl import load_workbook
import pandas as pd
document = Document()
workbook = load_workbook(filename = r"C:\Users\Desktop\excel_file.xlsx")
sheet = workbook['Sheet2']
tries = 5
for i in range(1, tries + 1):
table = document.add_table(rows = 4, cols = 2, style = 'Table Grid')
table.cell(0,0).text = "ACCT #"
table.cell(1,0).text = "NAME"
table.cell(0,1).text = sheet.cell(row = i, column = 1).value
table.cell(1,1).text = sheet.cell(row = i, column = 2).value
這給了我TypeError: 'int' object is not iterable'
它引用了這一行: table.cell(0,1).text = sheet.cell(row = i, column = 1).value
此外,Excel 文件中的數據在第一列中包含數字,在第二列中包含名稱,僅此而已。 不確定這是否重要。
嘗試 2:使用 Pandas
document = Document()
df = pd.read_excel(r"C:\Users\Desktop\excel_file.xlsx",sheet_name = None, header = None)
data = df["Sheet2"]
tries = 5
for i in range(1, tries + 1):
table = document.add_table(rows = 4, cols = 2, style = 'Table Grid')
table.cell(0,0).text = "ACCT #"
table.cell(1,0).text = "NAME"
table.cell(0,1).text = data.iloc[i, 0]
table.cell(1,1).text = data.iloc[i, 1]
這給了我: TypeError: 'numpy.int64' object is not iterable
and it references: table.cell(0,1).text = data.iloc[i, 0]
我不確定我做錯了什么或此時如何解決它。 任何幫助將非常感激!
這對我有用,
from docx import Document
from docx.shared import Pt
from openpyxl import load_workbook
import pandas as pd
def addTable(doc, df):
doc.add_paragraph('A plain paragraph having some ')
tabrows = df.shape[0]
tabcols =df.shape[1]
table = doc.add_table(rows = tabrows+1, cols = tabcols, style= 'Table Grid')
table.cell(0,0).text = "Account"
table.cell(0,1).text = 'Name'
for r in range(tabrows):
for c in range(tabcols):
table.cell(r+1,c).text = str(df.iloc[r,c])
doc.add_page_break()
def main():
dfin = pd.DataFrame({'Numbers':[1,2,3,4,5],'Words':['Alpha','Beta',
'Gamma', 'Delta', 'Epsilon']})
doc = Document()
addTable(doc, dfin)
doc.save('tstdoc.docx')
if __name__ == "__main__":
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.