我正在尝试通过我在头部导入的Win32COM客户端将列表导出到Excel。 我创建的对象编码如下,但我似乎无法将每个值导出到电子表格中自己的行。如果我能得到一个好的指针(除了放弃python !!:D),我将不胜感激。
class XcelExport():
def excel(self):
app = 'Excel'
xl = win32.gencache.EnsureDispatch('%s.Application' % app)
ss = xl.Workbooks.Open(r'C:\MyFile.xls')
sh = ss.ActiveSheet
xl.Visible = True
sleep(.1)
sh.Cells(1,1).Value = 'Export-to-%s : Items' % app
sleep(.1)
for i in EventTableRFT:
sh.Range("A").Value = i
sh.Cells(i+2,1).Value = "End of the List!"
xprt = XcelExport()
xprt.excel()
答案 0 :(得分:15)
由于您似乎喜欢我的回答/评论,所以这是一个恰当的答案:
Python Excel几乎可以满足你所需要的一切。如果你想要更集成但似乎有限的东西,那就有IronSpread。 XLRD和XLWT是很棒的软件包,但它们不支持* .xlsx文件。 IronSpread仅适用于Windows,仅支持'07和'10版本的Excel。每个都有它的警告。最后,你可以使用两者(编辑为* .xlsx,然后保存为* .xls(我有一个人对大* .xls文件有速度问题,但我的脚本从那个东西写了200mb的文本,如1分钟。))。
哦,我肯定会阅读(浏览)文档中的有趣功能,例如获取xlrd / xlwt的单元格类型等。这是值得的,只是因为它很短并且会为你节省实验的学习曲线。
xlwt的超短示例:
import xlwt
from tempfile import TemporaryFile
book = xlwt.Workbook()
sheet1 = book.add_sheet('sheet1')
supersecretdata = [34,123,4,1234,12,34,12,41,234,123,4,123,1,45123,5,43,61,3,56]
for i,e in enumerate(supersecretdata):
sheet1.write(i,1,e)
name = "random.xls"
book.save(name)
book.save(TemporaryFile())
xlrd的超短示例:
import xlrd
from xlrd import open_workbook
book = open_workbook('random.xls')
sheet1 = book.sheet_by_index(0)
data = []
for i in xrange(sheet1.nrows):
data.append(sheet1.cell(i,1).value)
答案 1 :(得分:1)
您缺少Range中的单元格行号,并且需要在循环的每次迭代后增加单元格行。
sh.Range("A1").Offset(0,x).Value = i
此更改应该有效。
class XcelExport():
def excel(self):
app = 'Excel'
xl = win32.gencache.EnsureDispatch('%s.Application' % app)
ss = xl.Workbooks.Open(r'C:\MyFile.xls')
sh = ss.ActiveSheet
xl.Visible = True
sleep(.1)
sh.Cells(1,1).Value = 'Export-to-%s : Items' % app
sleep(.1)
x=0
for i in EventTableRFT:
sh.Range("A1").Offset(0,x).Value = i #You need to increment the cell row
x+=1
sh.Cells(i+2,1).Value = "End of the List!"
xprt = XcelExport()
xprt.excel()
答案 2 :(得分:0)
class Signal(object):
def __init__(self, x, y):
self.x = x
self.y = y
def to_dict(self):
return {
'x': self.x,
'y': self.y,
}
def file_save_excel(dataset, filename, sheet_name, new_sheet):
dataset = dataset.applymap(lambda x: x.encode('unicode_escape').
decode('utf-8') if isinstance(x, str) else x)
print('Writing the processed dataset to excel file...')
writer = pd.ExcelWriter(filename, engine='openpyxl')
if os.path.exists(filename) and new_sheet:
book = openpyxl.load_workbook(filename)
writer.book = book
dataset.to_excel(writer, sheet_name=sheet_name, index=False)
writer.save()
writer.close()
return True
dataframe = pandas.DataFrame.from_records([s.to_dict() for s in signals])
file_save_excel(dataframe, 'FileName.xlsx', 'SheetName', True)