简体   繁体   English

对openpyxl、python3的疑惑

[英]Doubts on openpyxl, python3

He guys, I am just a beginner in Python3.伙计们,我只是 Python3 的初学者。 I have a question:我有个问题:

import openpyxl
from openpyxl.style import * 

As you can see that I am importing the openpyxl module, but why I need to import the second one in order to style fonts and cells an on.如您所见,我正在导入openpyxl模块,但为什么我需要导入第二个模块才能设置字体单元格的样式。

openpyxl is a package. openpyxl是一个包。 It contains modules, such as style .它包含模块,例如style You should import the package anyway (all package or individual items).您无论如何都应该导入包(所有包或单个项目)。 You can either:您可以:

import openpyxl
from openpyxl.style import *

then use style items like item1 , item2 or然后使用item1item2

from openpyxl import style

then use style items like style.item1 , style.item2然后使用样式项,如style.item1style.item2

You don't have to - you can just as easily do:你不必 - 你可以很容易地做到:

import openpyxl
openpyxl.styles.fonts()

Or:要么:

from openpyxl import style
style.fonts()

It comes down to personal preference.这取决于个人喜好。 Using * imports is generally frowned upon because there's a risk of polluting the namespace, but if you know this isn't going to happen, and you want to keep your lines of code shorter, it's acceptable.通常不赞成使用* imports,因为存在污染命名空间的风险,但如果您知道这不会发生,并且希望保持代码行更短,那么这是可以接受的。

You are importing openpyxl, which includes everything in openpyxl including openpyxl.style and everything inside that.您正在导入 openpyxl,它包括 openpyxl 中的所有内容,包括 openpyxl.style 以及其中的所有内容。 But say you would like to use X function of openpyxl.style, then you would have to write:但是如果你想使用 openpyxl.style 的 X 函数,那么你必须这样写:

openpyxl.style.X() 

If you write the second line you can simpy write:如果你写第二行,你可以简单地写:

X()

Basically the second line imports all the contents of the namespace openpyxl.style into your current namespace, removing the hassle of having to write openpyxl.style.基本上,第二行将命名空间 openpyxl.style 的所有内容导入您当前的命名空间,从而消除了必须编写 openpyxl.style 的麻烦。 everytime.每次。 Although it is generally a good practice to not merge namespaces like this, and not use尽管不合并这样的名称空间通常是一个好习惯,并且不使用

from _________ import *

Rather you can write相反你可以写

import openpyxl.style as op

and then use the X function as:然后将 X 函数用作:

op.X()

You can also omit the line您也可以省略该行

import openpyxl 

if you are not using anything else from openpyxl other than that included in openpyxl.style如果除了 openpyxl.style 中包含的以外,你没有使用 openpyxl 中的任何其他内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM