描述:
xlrd模塊的功能主要負(fù)責(zé)對Excel文件進(jìn)行讀取操作何暇,xlrd官網(wǎng)將其描述為:xlrd is a library for reading data and formatting information from Excel files in the historical .xls format.【注意historical】
注意:
該模塊只可以讀取xls格式的Excel文件轩猩,xls格式與xlms格式的區(qū)別簡單來講主要在于Excel對宏的處理上癌别,xlrd官網(wǎng)將其描述為:This library will no longer read anything other than .xls
files. For alternatives that read newer file formats, please see http://www.python-excel.org/.
警告:
截止2022年09月06日更新時荸镊,官方顯示以下模塊將不在繼續(xù)支持症见,在安全性上可以繼續(xù)保證,但在其可靠性上不在保證捺弦,xlrd官方將描述為:The following are also not supported but will safely and reliably be ignored:
- Charts, Macros, Pictures, any other embedded object, including embedded worksheets.
- VBA modules
- Formulas, but results of formula calculations are extracted.
- Comments
- Hyperlinks
- Autofilters, advanced filters, pivot tables, conditional formatting, data validation
Password-protected files are not supported and cannot be read by this library.
建議:
當(dāng)使用Python在進(jìn)行數(shù)據(jù)可視化處理時饮寞,將Python與Excel在數(shù)據(jù)可視化處理中各自應(yīng)發(fā)揮的優(yōu)勢和功能做好定位和區(qū)分,減少試圖通過Python來影響Excel內(nèi)容或希望Python可以一鍵操作數(shù)據(jù)的要求羹呵,各自發(fā)揮各自的優(yōu)勢骂际,這也是Python的精髓疗琉,Python官網(wǎng)將其描述為:Python is a programming language that lets you work quickly and integrate systems more effectively
官網(wǎng)地址:
https://xlrd.readthedocs.io/en/latest/
xlwt API:
https://xlrd.readthedocs.io/en/latest/api.html
- xlrd常用類有
1. book類
《該類用于鏈接工作簿冈欢,但該類不建議直接實(shí)例化使用,需要使用open_workbook_xls函數(shù)進(jìn)行工作簿鏈接盈简,官方將其描述為:Contents of a "workbook".warning::You should not instantiate this class yourself. You use the : class:Book
object that was returned when you called :func:~xlrd.open_workbook
.》
2. sheet類
《該類用于鏈接工作表凑耻,該類與book類一樣均不建議直接實(shí)例化使用太示,可由book類提供的sheet_by_name()函數(shù)返回的sheet類實(shí)例進(jìn)行操作,官方將其描述為:Contains the data for one worksheet. In the cell access functions, rowx
is a row index, counting from zero, and colx
is a column index, counting from zero. Negative values for row/column indexes and slice positions are supported in the expected fashion. For information about cell types and cell values, refer to the documentation of the :class:Cell
class.
.. warning:: You don't instantiate this class yourself. You access :class:Sheet
objects via the :class:~xlrd.book.Book
object that was returned when you called :func:xlrd.open_workbook
.》
-book類常用方法
1. xlrd.book.open_workbook_xls(*)
《該函數(shù)用來打開工作簿香浩,官方描述為:Open a spreadsheet file for data extraction.該函數(shù)接受若干參數(shù)类缤,其中用的最多的為filename參數(shù)和formatting_info參數(shù),其中filename參數(shù)指定要打開的工作簿邻吭,formatting_info參數(shù)指定是否讀取工作簿的樣式》
- 部分源碼如下
def open_workbook_xls(filename=None,
logfile=sys.stdout, verbosity=0, use_mmap=True,
file_contents=None,
encoding_override=None,
formatting_info=False, on_demand=False, ragged_rows=False,
ignore_workbook_corruption=False):
:param filename:
The path to the spreadsheet file to be opened.
:param logfile:
An open file to which messages and diagnostics are written.
:param verbosity:
Increases the volume of trace material written to the logfile.
:param use_mmap:
Whether to use the mmap module is determined heuristically.Use this arg to override
the result.Current heuristic: mmap is used if it exists.
:param file_contents:
A string or an :class:`mmap.mmap` object or some other behave-alike object. If
``file_contents`` is supplied, ``filename`` will not be used, except (possibly)
in messages.
:param encoding_override:
Used to overcome missing or bad codepage information in older-version files. See :
doc:`unicode`.
:param formatting_info:
The default is ``False``, which saves memory. In this case, "Blank" cells, which
are those with their own formatting information but no data, are treated as empty
by ignoring the file's ``BLANK`` and ``MULBLANK`` records. This cuts off any bottom
or right "margin" of rows of empty or blank cells. Only :meth:`~xlrd.sheet.Sheet.cell_value`
and :meth:`~xlrd.sheet.Sheet.cell_type` are available.
When ``True``, formatting information will be read from the spreadsheet file. This
provides all cells, including empty and blank cells. Formatting information is available
for each cell.
Note that this will raise a NotImplementedError when used with an xlsx file.
:param on_demand:
Governs whether sheets are all loaded initially or when demanded by the caller. See :doc:
`on_demand`.
:param ragged_rows:
The default of ``False`` means all rows are padded out with empty cells so that all rows
have the same size as found in :attr:`~xlrd.sheet.Sheet.ncols`.
``True`` means that there are no empty cells at the ends of rows. This can result in
substantial memory savings if rows are of widely varying sizes. See also the :meth:
`~xlrd.sheet.Sheet.row_len` method.
:param ignore_workbook_corruption:
This option allows to read corrupted workbooks.
When ``False`` you may face CompDocError: Workbook corruption.
When ``True`` that exception will be ignored.
:returns:
An instance of the :class:`~xlrd.book.Book` class.
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
2.xlrd.book.nsheets
《該方法為book類屬性餐弱,記錄了該工作簿的工作表(sheet)數(shù)量》
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
print(book.nsheets)
輸出:1
3.xlrd.book.sheets()
《返回整個工作簿的所有工作表(sheet)并以數(shù)組形式返回》
- 部分源碼如下
def sheets(self):
"""
:returns: A list of all sheets in the book.
All sheets not already loaded will be loaded.
"""
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
print(book.nsheets)
print(book.sheet_names())
print(book.sheets())
輸出:1
輸出:FirstSheet
輸出:[Sheet 0:<FistSheet>]
4.xlrd.book.sheet_names()
《返回工作簿中所有工作表(sheet)的名稱》
- 部分源碼如下
def sheet_names(self):
"""
:returns:
A list of the names of all the worksheets in the workbook file.
This information is available even when no sheets have yet been
loaded.
"""
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
print(book.nsheets)
print(book.sheet_names())
輸出:1
輸出:FirstSheet
5.xlrd.book.sheet_loaded(sheet_name_or_index)
《返回參數(shù)指定的工作表是否裝載完畢,若是返回TRUE囱晴,否則返回FALSE》
- 部分源碼如下
def sheet_loaded(self, sheet_name_or_index):
"""
:param sheet_name_or_index: Name or index of sheet enquired upon
:returns: ``True`` if sheet is loaded, ``False`` otherwise.
.. versionadded:: 0.7.1
"""
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
print(book.nsheets)
print(book.sheet_names())
print(book.sheets())
print(book.sheet_loaded(0))
print(book.sheet_loaded(book.sheet_names()[0]))
print(book.sheet_loaded("FirstSheet"))
輸出:1
輸出:FirstSheet
輸出:[Sheet 0:<FistSheet>]
輸出:TRUE
輸出:TRUE
輸出:TRUE
6.xlrd.book.sheet_by_name(sheet_name)
7.xlrd.book.sheet_by_index(sheetx)
《以上兩個函數(shù)都用來打開工作表膏蚓,第一個函數(shù)使用工作表的名稱打開,第二個函數(shù)使用工作表在工作簿中的索引打開》
- 部分源碼如下
def sheet_by_name(self, sheet_name):
"""
:param sheet_name: Name of the sheet required.
:returns: A :class:`~xlrd.sheet.Sheet`.
"""
def sheet_by_index(self, sheetx):
"""
:param sheetx: Sheet index in ``range(nsheets)``
:returns: A :class:`~xlrd.sheet.Sheet`.
"""
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
openFirstBook1 = book.sheet_by_name(book.sheet_names()[0])
openFirstBook2 = book.sheet_by_index(0)
print(openFirstBook1.name)
print(openFirstBook2.name)
輸出:FirstSheet
輸出:FirstSheet
8.xlrd.book.xf_list
《該方法是book類的屬性畸写,記錄了該工作簿中工作表的樣式集合驮瞧,只有將open_workbook_xls()函數(shù)中,formatting_info設(shè)置為TRUE時枯芬,xf_list屬性才會保存樣式论笔,官方描述為:A list of :class:~xlrd.formatting.XF
class instances, each corresponding to an XF
record. 返回集合的索引由具體工作表中的cell_xf_index()函數(shù)返回的單元格樣式提供》
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
print(book.xf_list[0])
第一個輸出:<xlrd.formatting.XF object at 0x10bf2a550>
9. xlrd.book.font_list
《該方法同樣是book類的屬性,記錄了該工作簿中單元格的字體樣式集合千所,官方描述為:A list of :class:~xlrd.formatting.XF
class instances, each corresponding to an XF
record. 注意狂魔!返回集合的索引由單元格樣式的字體索引提供,而不是由各工作表中cell_xf_index()函數(shù)指定的單元格樣式提供》
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
firstBook = book.sheet_by_name(book.sheet_names()[0])
cellStyle = firstBook.cell_xf_index(1,0)
xfStyle = book.xf_list[cellStyle]
#注意book.font_list的參數(shù)
xfFontStyle = book.font_list[xfStyle.font_index]
print(xfStyle.font_index)
print(xfFontStyle.name)
print(xfFontStyle.italic)
第一個輸出:9
第二個輸出:Arial
第三個輸出:0
- sheet類常用方法
1. xlrd.sheet.nrows
2. xlrd.sheet.ncols
《以上兩個方法為sheet類的屬性淫痰,記錄了該工作表的總行數(shù)和總列數(shù)》
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
openFirstBook1 = book.sheet_by_name(book.sheet_names()[0])
print(openFirstBook1.nrows,openFirstBook1.ncols)
輸出:4 4
3. xlrd.sheet.cell_value(rowx, colx)
4. xlrd.sheet.cell_type(rowx, colx)
5. xlrd.sheet.cell_xf_index(rowx, colx)
6. xlrd.sheet.cell(rowx, colx)
《函數(shù)3返回參數(shù)指定的單元格內(nèi)容毅臊,參數(shù)由行數(shù)和列數(shù)構(gòu)成,函數(shù)4返回參數(shù)指定的單元格類型黑界,函數(shù)5返回參數(shù)指定的單元格樣式索引管嬉,該索引來自book.Book.xf_list數(shù)組保存的單元格樣式,函數(shù)6返回參數(shù)指定的單元格類型朗鸠、內(nèi)容蚯撩、樣式索引》
- xlrd.sheet.cell_xf_index(rowx,colx)部分源碼
def cell_xf_index(self, rowx, colx):
"""
XF index of the cell in the given row and column.
This is an index into :attr:`~xlrd.book.Book.xf_list`.
.. versionadded:: 0.6.1
"""
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
openFirstBook1 = book.sheet_by_name(book.sheet_names()[0])
print(openFirstBook1.cell_value(0,0))
print(openFirstBook1.cell_type(0,0))
print(openFirstBook1.cell_xf_index(0,0))
print(openFirstBook1.cell(0,0))
第一個輸出:林州歡迎你
第二個輸出:1
第三個輸出:17
第四個輸出:text:'林州歡迎你' (XF:17)
其中type項(xiàng)輸出為1,1代表了單元格的數(shù)據(jù)類型烛占,詳細(xì)列表如下
0:empty
1:text
2:number
3:date
4:boolean
5:error
6. xlrd.sheet.row_len(rowx)
7. xlrd.sheet.row(rowx)
8. xlrd.sheet.get_rows()
《函數(shù)6返回參數(shù)指定的行所包括的單元格數(shù)量胎挎,實(shí)際上以最大單元格數(shù)量所在行的數(shù)量為準(zhǔn),函數(shù)7返回參數(shù)指定的行的內(nèi)容忆家,信息構(gòu)成與xrld.sheet.cell()函數(shù)返回一致犹菇,函數(shù)8返回所有行的內(nèi)容,以迭代器體現(xiàn)》
- 部分源碼如下
def row_len(self, rowx):
"""
Returns the effective number of cells in the given row. For use with
``open_workbook(ragged_rows=True)`` which is likely to produce rows
with fewer than :attr:`~Sheet.ncols` cells.
.. versionadded:: 0.7.2
"""
def row(self, rowx):
"""
Returns a sequence of the :class:`Cell` objects in the given row.
"""
def get_rows(self):
"Returns a generator for iterating through each row."
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
openFirstBook1 = book.sheet_by_name(book.sheet_names()[0])
print(openFirstBook1.row_len(16))
print(openFirstBook1.row(0))
print(openFirstBook1.get_rows())
for key in openFirstBook1.get_rows():
print(key)
第一個輸出:16【16實(shí)際上是第2行最大的單元格數(shù)量芽卿,代碼上表示為1】
第二個輸出:[text:'林州歡迎你' (XF:57), empty:'' (XF:15), empty:'' (XF:15), empty:'' (XF:15), empty:'' (XF:15), empty:'' (XF:15), empty:'' (XF:15), empty:'' (XF:15)]
第三個輸出:<generator object Sheet.get_rows.<locals>.<genexpr> at 0x100f903d0>
第四個輸出:每行的內(nèi)容揭芍,類型同第二個輸出
9. xlrd.sheet.row_types(rowx, start_colx=0, end_colx=None)
10. xlrd.sheet.row_values(rowx, start_colx=0, end_colx=None)
11. xlrd.sheet.col_types(colx, start_rowx=0, end_rowx=None)
12. xlrd.sheet.col_values(colx, start_rowx=0, end_rowx=None)
《函數(shù)9返回參數(shù)指定的行和限定列數(shù)的類型,函數(shù)10返回參數(shù)指定的行和限定列數(shù)的內(nèi)容卸例,函數(shù)11返回指定的列和限定的行數(shù)的類型称杨,函數(shù)12返回指定的列和限定的行數(shù)的內(nèi)容》
- 注意
其中函數(shù)9肌毅、10、11姑原、12中用于限定列數(shù)或行數(shù)的參數(shù)悬而,其本質(zhì)上是指定取列數(shù)或行數(shù)的多少,而不是指定其范圍锭汛,其部分源碼實(shí)現(xiàn)如下
def row_types(self, rowx, start_colx=0, end_colx=None):
"""
Returns a slice of the types of the cells in the given row.
"""
if end_colx is None:
return self._cell_types[rowx][start_colx:]
return self._cell_types[rowx][start_colx:end_colx]
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
openFirstBook1 = book.sheet_by_name(book.sheet_names()[0])
print(openFirstBook1.row_types(2,2,3)) #注意這里的2,2,3笨奠,代表從第2行開始(實(shí)際上是第三行),從2列開始取1列(3-2)唤殴,而不是從第2列開始取到第3列取2列
print(openFirstBook1.row_values(2,2,3))
print(openFirstBook1.col_types(0,0,17))
print(openFirstBook1.col_values(0,0,17))
第一個輸出:array('B', [1])
第二個輸出:['紅旗渠歡迎你']
第三個輸出:[1, 2, 1, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 1]
第四個輸出:['林州歡迎你', 12345.0, '阿斯達(dá)', '', '', '', '', '', 123.0, '', '', ' 阿斯達(dá)', '', '', '', '', ' sad']
13. xlrd.sheet.row_slice(rowx, start_colx=0, end_colx=None)
14. xlrd.sheet.col_slice(olx, start_rowx=0, end_rowx=None)
《函數(shù)13返回參數(shù)指定的行艰躺,限定的列的單元格類型、內(nèi)容、樣式索引,與xlrd_sheet_cell()函數(shù)返回值的類型完全相同傻铣,函數(shù)14則返回指定的列,限定的行的數(shù)據(jù)页响,數(shù)據(jù)構(gòu)成同上》
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
openFirstBook1 = book.sheet_by_name(book.sheet_names()[0])
print(openFirstBook1.row_slice(1,1,4))
print(openFirstBook1.col_slice(1,1,6))
第一個輸出:[text:'太行大峽谷歡迎你' (XF:57), empty:'' (XF:59), number:345.0 (XF:59)]
第二個輸出:[text:'太行大峽谷歡迎你' (XF:57), empty:'' (XF:15), empty:'' (XF:15), empty:'' (XF:15), text:'阿斯達(dá)' (XF:60)]
15. xlrd.sheet.hyperlink_list
16. xlrd.sheet.hyperlink_map
《方法15是sheet類的屬性,記錄了工作表中所有的超鏈接對象段誊,方法16同樣也是sheet類的屬性闰蚕,記錄了工作表中所有超鏈接對象及該對象的位置,該位置是代碼表示位置而非視覺位置连舍,如第3列没陡,代碼位置顯示為第4列(起步0),通過這兩個方法獲得的超鏈接對象均可通過Hyperlink類屬性來進(jìn)行訪問索赏,該類記錄了關(guān)于超鏈接的部分內(nèi)容盼玄,官方描述為:Contains the attributes of a hyperlink. Hyperlink objects are accessible through :attr:Sheet.hyperlink_list
and :attr:Sheet.hyperlink_map
.》
- Hyperlink類部分源碼如下
class Hyperlink(BaseObject):
#: Index of first row
frowx = None
#: Index of last row
lrowx = None
#: Index of first column
fcolx = None
#: Index of last column
lcolx = None
#: Type of hyperlink. Unicode string, one of 'url', 'unc',
#: 'local file', 'workbook', 'unknown'
type = None
#: The URL or file-path, depending in the type. Unicode string, except
#: in the rare case of a local but non-existent file with non-ASCII
#: characters in the name, in which case only the "8.3" filename is
#: available, as a :class:`bytes` (3.x) or :class:`str` (2.x) string,
#: *with unknown encoding.*
url_or_path = None
#: Description.
#: This is displayed in the cell,
#: and should be identical to the cell value. Unicode string, or ``None``.
#: It seems impossible NOT to have a description created by the Excel UI.
desc = None
#: Target frame. Unicode string.
#:
#: .. note::
#: No cases of this have been seen in the wild.
#: It seems impossible to create one in the Excel UI.
target = None
#: The piece after the "#" in
#: "http://docs.python.org/library#struct_module", or the ``Sheet1!A1:Z99``
#: part when type is "workbook".
textmark = None
g#: The text of the "quick tip" displayed when the cursor
#: hovers over the hyperlink.
quicktip = None
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
openFirstBook1 = book.sheet_by_name(book.sheet_names()[0])
print(openFirstBook1.hyperlink_list)
print(openFirstBook1.hyperlink_map)
print(openFirstBook1.hyperlink_list[0].url_or_path,openFirstBook1.hyperlink_list[0].textmark,openFirstBook1.hyperlink_list[0].desc,openFirstBook1.hyperlink_list[0].target,openFirstBook1.hyperlink_list[0].quicktip)
第一個輸出:[<xlrd.sheet.Hyperlink object at 0x1037e2350>]
第二個輸出:{(12, 1): <xlrd.sheet.Hyperlink object at 0x1037e2350>}
第三個輸出:https://max.book118.com/html/2019/0109/8115017112002000.shtm None https://max.book118.com/html/2019/0109/8115017112002000.shtm None None
17.xlrd.sheet.merged_cells
《該方法為sheet類的屬性,記錄了合并單元格的范圍潜腻,官方描述為:List of address ranges of cells which have been merged》
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
openFirstBook1 = book.sheet_by_name(book.sheet_names()[0])
print(openFirstBook1.merged_cells)
第一個輸出:[(3, 4, 0, 2)]
該輸出表達(dá)的內(nèi)容同row_values()中第1埃儿、2個參數(shù)表達(dá)的意思相同
即表示為從第4行開始(視覺行:3+1),合并1行(4-3)
從第1列開始(視覺行:0+1)融涣,合并2列童番,(2-0)
18. xlrd.sheet.cell_xf_index(rowx, colx)
《該函數(shù)返回參數(shù)指定單元格的xf樣式,官方描述為:XF index of the cell in the given row and column.This is an index into :attr:~xlrd.book.Book.xf_list
.》
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
firstBook = book.sheet_by_name(book.sheet_names()[0])
cellStyle = firstBook.cell_xf_index(1,0)
xfStyle = book.xf_list[cellStyle]
print(xfStyle)
print(xfStyle.protection.cell_locked)
print(xfStyle.protection.formula_hidden)
第一個輸出:<xlrd.formatting.XF object at 0x10de2a910>
第二個輸出:1
第三個輸出:0
19. xlrd.sheet.rowinfo_map
20. xlrd.sheet.colinfor_map
《方法19和方法20均為sheet類的屬性威鹿,其方法19記錄了行的相關(guān)信息剃斧,官方描述為:Height and default formatting information that applies to a row in a sheet. Derived from ROW
records. 方法20記錄了列的相關(guān)信息,官方描述為:Width and default formatting information that applies to one or more columns in a sheet. Derived from COLINFO
records.》
- 部分源碼如下
class Rowinfo(BaseObject):
if _USE_SLOTS:
__slots__ = (
"height",
"has_default_height",
"outline_level",
"outline_group_starts_ends",
"hidden",
"height_mismatch",
"has_default_xf_index",
"xf_index",
"additional_space_above",
"additional_space_below",
)
class Colinfo(BaseObject):
#: Width of the column in 1/256 of the width of the zero character,
#: using default font (first ``FONT`` record in the file).
width = 0
#: XF index to be used for formatting empty cells.
xf_index = -1
#: 1 = column is hidden
hidden = 0
#: Value of a 1-bit flag whose purpose is unknown
#: but is often seen set to 1
bit1_flag = 0
#: Outline level of the column, in ``range(7)``.
#: (0 = no outline)
outline_level = 0
#: 1 = column is collapsed
collapsed = 0
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
firstBook = book.sheet_by_name(book.sheet_names()[0])
print(firstBook.rowinfo_map[0].height,firstBook.rowinfo_map[0].hidden,firstBook.rowinfo_map[0].xf_index)
print(firstBook.colinfo_map[0].width,firstBook.colinfo_map[0].hidden,firstBook.colinfo_map[0].collapsed)
第一個輸出:260 0 -1
第二個輸出:7893 0 0
3. xldata類
《該類主要用于單元格時間數(shù)據(jù)的處理忽你,官方描述為:Tools for working with dates and times in Excel files.The conversion from days
to (year, month, day)
starts with an integral "julian day number" aka JDN.
FWIW:
- JDN 0 corresponds to noon on Monday November 24 in Gregorian year -4713.
More importantly:
- Noon on Gregorian 1900-03-01 (day 61 in the 1900-based system) is JDN 2415080.0
-
Noon on Gregorian 1904-01-02 (day 1 in the 1904-based system) is JDN 2416482.0》
加入時間的工作簿
- xldata類常用方法
1. xlrd.xldata.xldate_as_tuple(xldate, datemode)
《該函數(shù)將參數(shù)指定的單元格時間數(shù)據(jù)轉(zhuǎn)換為時間元組類型的數(shù)據(jù)幼东,detemode指定要轉(zhuǎn)換基準(zhǔn)時間類型,0表示從1900-01-01號開始計算,1表示從1904-01-01號開始計算筋粗,官方描述為:Convert an Excel number (presumed to represent a date, a datetime or a time) into a tuple suitable for feeding to datetime or mx.DateTime constructors.》
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
openFirstBook1 = book.sheet_by_name(book.sheet_names()[0])
print(openFirstBook1.col_values(3,9)[0])
convertData1 = xlrd.xldate.xldate_as_tuple(openFirstBook1.col_values(3,9)[0],0)
convertData2 = xlrd.xldate.xldate_as_tuple(openFirstBook1.col_values(3,9)[0],1)
print(convertData1)
print(convertData2)
#元組數(shù)據(jù)操作
serialData = '%d-%d-%d'%(convertData1[0],convertData1[1],convertData1[2])
print(serialData)
第一個輸出:44812.0
第二個輸出:(2022, 9, 8, 0, 0, 0)
第三個輸出:(2026, 9, 9, 0, 0, 0)
第四個輸出:2022-9-8
2. xlrd.xldata.xldate_as_datetime(xldate, datemode)
《該函數(shù)將參數(shù)指定的單元格時間數(shù)據(jù)轉(zhuǎn)換為時間類型的數(shù)據(jù),detemode參數(shù)同xlrd.xldata.xldata_as_tuple()函數(shù)相同炸渡,官方描述為: Convert an Excel date/time number into a :class:datetime.datetime
object.》
例:
book = xlrd.open_workbook_xls("TheRedCanyon.xls",formatting_info=True)
openFirstBook1 = book.sheet_by_name(book.sheet_names()[0])
print(openFirstBook1.col_values(3,9)[0])
converData1 = xlrd.xldate.xldate_as_datetime(openFirstBook1.col_values(3,9)[0],1)
converData2 = xlrd.xldate.xldate_as_datetime(openFirstBook1.col_values(3,9)[0],0)
print(converData1)
print(converData2)
#時間對象處理
print(convertData2.strftime("%Y/%m/%d"))
第一個輸出:2026-09-09 00:00:00
第二個輸出:2022-09-08 00:00:00
第三個輸出:2022/09/08