我正在写入2张Excel文件-sheet1
和geodata
。
test_df = DataFrame({'col1':[1,2,3,4], 'col2':['a','b','c','d']})
test2_df = DataFrame({'lat':[89.0, 34.89, 23.56],'lng':[45.6, 67.9, 89.0]}, index = ['Paris','Spain','Barcelona'])
writer = pd.ExcelWriter('./test_book.xlsx', engine = 'xlsxwriter')
test_df.to_excel(writer, 'sheet1')
test2_df.to_excel(writer, 'geodata')
writer.save()
writer.close()
稍后将另一个新工作表sheet3
写入同一文件,并将一些其他数据写入geodata
。当我运行下面的代码块并尝试从文件夹中打开excel工作表时,我收到一条错误消息,指出它无法打开。
test3_df = DataFrame({'col1':[3,5,6], 'col2':['x','y','k']})
test2_new_df = DataFrame({'lat':[44.6,38.9],'lng':[35.7,89.3]},index=['US','UK'])
from openpyxl import load_workbook
writer = pd.ExcelWriter('./test_book.xlsx', engine = 'openpyxl')
writer.book = load_workbook('./test_book.xlsx')
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
test3_df.to_excel(writer,'Sheet3')
test2_new_df.to_excel(writer, 'geodata',header = False, startrow =len(test2_df)+1)
writer.close()
当我第二次运行此代码块时,便可以打开该文件。但是我在索引'US'
中两次附加了与索引'UK'
和geodata
相关的新值。我尝试了多种方法,但是第一次运行此代码后无法打开文件。
答案 0 :(得分:1)
您不应在代码中间import
库。始终import
位于代码顶部。我已经复制了您的代码,并对xlsxwriter
作为引擎做了一个小小的更改,但生成的文件没有任何问题。
import openpyxl
from openpyxl import *
from openpyxl.styles import NamedStyle
from openpyxl import load_workbook
import pandas as pd
test_df = pd.DataFrame({'col1':[1,2,3,4], 'col2':['a','b','c','d']})
test2_df = pd.DataFrame({'lat':[89.0, 34.89, 23.56],'lng':[45.6, 67.9, 89.0]}, index = ['Paris','Spain','Barcelona'])
writer = pd.ExcelWriter('./test_book.xlsx', engine = 'openpyxl') #I changed this to openpyxl, from xlsxwriter
test_df.to_excel(writer, 'sheet1')
test2_df.to_excel(writer, 'geodata')
writer.save()
writer.close()
test3_df = pd.DataFrame({'col1':[3,5,6], 'col2':['x','y','k']})
test2_new_df = pd.DataFrame({'lat':[44.6,38.9],'lng':[35.7,89.3]},index=['US','UK'])
writer = pd.ExcelWriter('./test_book.xlsx', engine = 'openpyxl')
writer.book = load_workbook('./test_book.xlsx')
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
test3_df.to_excel(writer,'Sheet3')
test2_new_df.to_excel(writer, 'geodata',header = False, startrow =len(test2_df)+1)
writer.close()
输出: