如何用openpyxl为现有Excel表格添加新列并保留公式?
问题:扩展Excel表格并保留公式
我有一个包含现有表格及引用表格数据公式的模板电子表格,模板表格初始包含一行空数据。我需要为表格添加数据(行和列),同时确保原有公式能正常运行。
添加行的功能已经通过代码实现,但添加列时遇到了问题:
- 尝试直接修改表格的范围(扩大列数)会导致Excel文件损坏,重新打开后表格被Excel完全移除
- 尝试通过
table.column_names.append()添加新列名没有任何效果 - 用替换表格的方式添加列会破坏原有公式,因此不可行
以下是我的代码片段:
sSheetName = 'test' workbook = openpyxl.load_workbook(excelDumpFilename) sheet=workbook[sSheetName] dfCSVData = pd.read_csv(os.path.join(sCSVLocation,sCSVFile)) sheetRow = 2 # loop around each row in the CSV data for CSVrow in dataframe_to_rows(dfCSVData, header=False, index=False): sheetCol = 2 sheet.insert_rows(sheetRow, 1) # loop around each value of the data row for CSVvalue in CSVrow: sheet.cell(row=sheetRow, column=sheetCol).value=CSVvalue sheetCol+=1 sheetRow+=1 table = sheet.tables[sSheetName] currentTitleCount = len(table.column_names) tableRows = dfCSVData.shape[0] tableCols = dfCSVData.shape[1] # Update table titles for non-generic fields for index in range(currentTitleCount, tableCols): sheet.cell(row=2, column=tableColStart+index).value=dfCSVData.columns[index] table.column_names.append( dfCSVData.columns[index] ) newRange=openpyxl.worksheet.cell_range.CellRange( min_row=tableRowStart, min_col=tableColStart, max_row=tableRowStart + tableRows, max_col=tableColStart + tableCols - 1 #max_col=tableColStart + currentTitleCount - 1 ) tTable.ref=newRange.coord tTable.autoFilter.ref=newRange.coord workbook.save(excelDumpFilename)
注:dfCSVData包含新的表格数据,其维度比模板表格大。
内容的提问来源于stack exchange,提问作者Richard
相关产品推荐
相关产品推荐

