[英]Using a function from another file to write to excel with xlsx
I have two python files: 我有两个python文件:
1- writerCode.py: 1- writerCode.py:
import xlsxwriter
workbook = xlsxwriter.Workbook('demo.xlsx')
ws = workbook.add_worksheet()
def writeTo(x,y,array):
j = 0
while j < (len(array)):
ws.write(x,y,array[j])
j +=1
x +=1
return;
workbook.close()
2- testingCode.py: 2- testingCode.py:
from writerCode import *
an = ['123','234','123','432','123']
writeTo(0,0,an)
I want to import an[] items to excel. 我想将[]项导入excel。
When I run testingCode.py it creates 'demo.xlsx' with NOTHING in it. 当我运行testingCode.py时,它会创建带有NOTHING的'demo.xlsx'。 The excel file is empty meaning that it does not import an[] to the excel file as intended. excel文件为空意味着它不会按预期将[]导入excel文件。
I was wondering if anybody knows what the problem is?? 我想知道是否有人知道问题是什么?
The problem is not "Using a function from another file" 问题不是“使用其他文件中的函数”
The excel file is empty meaning that it does not import an[] to the excel file as intended. excel文件为空意味着它不会按预期将[]导入excel文件。
It could also mean that the part of your code controlling Excel does not work. 它也可能意味着控制Excel的代码部分不起作用。
test2.py: test2.py:
def mydef(d):
print(d)
test.py: test.py:
from test2 import *
data = "hello"
mydef(data)
results in 结果是
hello
So it's not that. 所以不是那样的。
It's probably that you are closing your workbook right after you open it. 可能是您在打开工作簿后立即关闭工作簿。 All the code is run on import, except for the function. 除函数外,所有代码都在导入时运行。
Ugly quick fix (restructure your code): 丑陋的快速修复(重构您的代码):
workbook.close()
after calling writeTo()
. 在调用writeTo()
。
xlsxwriter
should be raising an Exception when a closed Workbook/Worksheet is being written to, but it doesn't:
xlsxwriter
应该在写入关闭的工作簿/工作表时引发异常,但它不会:
import xlsxwriter workbook = xlsxwriter.Workbook('demo.xlsx') ws = workbook.add_worksheet() workbook.close() ws.write(0,0,"hello")
indeed results in a valid XSLX file with no data in the cell. 确实会导致单元格中没有数据的有效XSLX文件。
You are trying to import closed Workbook in
testingCode.py
, you can't write to a closed workbook. 您正在尝试在testingCode.py
导入已关闭的工作簿,您无法写入已关闭的工作簿。
So, replace workbook.close()
to testingCode.py
. 因此,将workbook.close()
替换为testingCode.py
。 That way you are closing workbook after calling the function writeTo(x, y, array)
. 这样,您在调用函数writeTo(x, y, array)
后关闭工作簿。
And try to use for
loop, because while
loop works but makes your code looks bit complex to read. 并尝试使用for
循环,因为while
循环工作,但使您的代码看起来有点复杂。 And make your code looks neat by adding spaces after ,
. ,使你的代码看起来后,通过添加空格整齐,
。 These spaces makes your code more readable. 这些空间使您的代码更具可读性。
def writeTo(x, y, array):
for item in (array):
ws.write(x, y, item)
x += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.