将值写入python中pandas工作表中的特定单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39805677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write values to a particular cell in a sheet in pandas in python
提问by penta
I have an excel sheet, which already has some values in some cells.
我有一个 excel 表,它在某些单元格中已经有一些值。
For ex :-
例如:-
A B C D
1 val1 val2 val3
2 valx valy
I want pandas to write to specific cells without touching any other cells,sheet etc
我希望熊猫在不接触任何其他单元格、工作表等的情况下写入特定单元格
This is the code i tried.
这是我试过的代码。
import pandas as pd
from openpyxl import load_workbook
df2 = pd.DataFrame({'Data': [13, 24, 35, 46]})
book = load_workbook('b.xlsx')
writer = pd.ExcelWriter('b.xlsx', engine='openpyxl')
df2.to_excel(writer, "Sheet1", startcol=7,startrow=6)
writer.save()
However this code deletes the older cell values.
但是,此代码会删除较旧的单元格值。
I have reffered to :- How to write to an existing excel file without overwriting data (using pandas)?but this solution does not work.
我已经提到:-如何在不覆盖数据的情况下写入现有的 excel 文件(使用 Pandas)?但这个解决方案不起作用。
采纳答案by penta
I was not able to do what was asked by me in the question by using pandas, but was able to solve it by using Openpyxl
.
我无法通过使用熊猫来完成我在问题中提出的问题,但能够通过使用Openpyxl
.
I will write few code snippets which would help in achieving what was asked.
我将编写一些有助于实现所要求的代码片段。
import openpyxl
srcfile = openpyxl.load_workbook('docname.xlsx',read_only=False, keep_vba= True)#to open the excel sheet and if it has macros
sheetname = srcfile.get_sheet_by_name('sheetname')#get sheetname from the file
sheetname['B2']= str('write something') #write something in B2 cell of the supplied sheet
sheetname.cell(row=1,column=1).value = "something" #write to row 1,col 1 explicitly, this type of writing is useful to write something in loops
srcfile.save('newfile.xlsm')#save it as a new file, the original file is untouched and here I am saving it as xlsm(m here denotes macros).
So Openpyxl writes to a purticular cell, without touching the other sheets,cells etc. It basically writes to a new file respecting the properties of the original file
所以 Openpyxl 写入一个特定的单元格,而不触及其他工作表、单元格等。它基本上写入一个尊重原始文件属性的新文件
回答by MaxU
UPDATE2:appending data to existing Excel sheet, preserving other (old) sheets:
UPDATE2:将数据附加到现有 Excel 工作表,保留其他(旧)工作表:
import pandas as pd
from openpyxl import load_workbook
fn = r'C:\Temp\.data\doc.xlsx'
df = pd.read_excel(fn, header=None)
df2 = pd.DataFrame({'Data': [13, 24, 35, 46]})
writer = pd.ExcelWriter(fn, engine='openpyxl')
book = load_workbook(fn)
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df.to_excel(writer, sheet_name='Sheet1', header=None, index=False)
df2.to_excel(writer, sheet_name='Sheet1', header=None, index=False,
startcol=7,startrow=6)
writer.save()
UPDATE:your Excel file doesn't have a header, so you should process it accordingly:
更新:您的 Excel 文件没有标题,因此您应该相应地处理它:
In [57]: df = pd.read_excel(fn, header=None)
In [58]: df
Out[58]:
0 1
0 abc def
1 ghi lmn
In [59]: df2
Out[59]:
Data
0 13
1 24
2 35
3 46
In [60]: writer = pd.ExcelWriter(fn)
In [61]: df.to_excel(writer, header=None, index=False)
In [62]: df2.to_excel(writer, startcol=7,startrow=6, header=None, index=False)
In [63]: writer.save()
OLD answer:
旧答案:
You can use the following trick:
您可以使用以下技巧:
first read the existing contents of the excel file into a new DF:
首先将excel文件的现有内容读入新的DF:
In [17]: fn = r'C:\Temp\b.xlsx'
In [18]: df = pd.read_excel(fn)
In [19]: df
Out[19]:
A B C D
0 val1 NaN val3 val4
1 val11 val22 NaN val33
now we can write it back and append a new DF2:
现在我们可以写回它并附加一个新的 DF2:
In [20]: writer = pd.ExcelWriter(fn)
In [21]: df.to_excel(writer, index=False)
In [22]: df2.to_excel(writer, startcol=7,startrow=6, header=None)
In [23]: writer.save()
回答by selvakumar
Using pandas to read the excel and append the file
使用pandas读取excel并追加文件
def getpayment_excel(request):
df = pd.read_excel(open(str(settings.MEDIA_ROOT)+"/"+"details.xlsx", 'rb'), sheetname='Sheet1')
XLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
response = HttpResponse(content_type=XLSX_MIME)
response['Content-Disposition'] = 'attachment; filename="PythonExport.xlsx"'
writer = pd.ExcelWriter(response, engine='xlsxwriter')
df.loc[0,'Bank Name'] = "ICICIW"
df.to_excel(writer, 'Sheet1', index=False)
writer.save()
return response