一、excel操作模塊 xlrd xlwt
1.xlrd 模塊用來讀excel
import xlrd #導入讀excel的模塊 book = xlrd.open_workbook('d_product.xls') sheet = book.sheet_by_index(0) #根據下標獲取sheet頁,下標從0開始,即第一個sheet頁的下標爲0 #sheet = book.sheet_by_name('sheet1') #根據名字獲取sheet頁數據 #讀單元格內容 print(book.nsheets)#獲取電子表格中sheet頁的個數,返回的是一個int類型的數字
print(book.sheet_names()) #獲取電子表格sheet頁的所有名字,放在一個list當中# 返回的類型是class 'xlrd.sheet.Cell',如果sheet頁爲空會報錯IndexError: list index out of range
print(sheet.cell(0,0))
print(sheet.cell(0,0).value) #獲取單元格內容#獲取一整行內容 sheet.row_values()#print(sheet.row_values(0)) #獲取第1行的內容,結果存放在一個list當中#獲取一整列內容 sheet.col_values()#print(sheet.col_values(0)) #獲取第1列的內容,結果存放在一個list當中#獲取所有的行數#print(sheet.nrows) #獲取到excel當中有多少行#獲取所有的列數#print(sheet.ncols) #獲取到excel中的有多少列#循環獲取到每行的數據for i in range(sheet.nrows): print( sheet.row_values(i))#循環獲取到每列的數據# for i in range(sheet.ncols):# print( sheet.col_values(i))
方法解析
1)xlrd.open_workbook('c:\abc.xls') #打開一個電子表格用來提取數據
def open_workbook(filename=None, logfile=sys.stdout, verbosity=0, use_mmap=USE_MMAP, file_contents=None, encoding_override=None, formatting_info=False, on_demand=False, ragged_rows=False, ): """ Open a spreadsheet file for data extraction. :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. :returns: An instance of the :class:`~xlrd.book.Book` class. """
2.xlwt用來寫excel
import xlwt book = xlwt.Workbook() sheet = book.add_sheet('sheet1',cell_overwrite_ok=True) #book.get_sheet() #第一個爲行號,第二個參數列號,第三列單元格內容 sheet.write(0,0) sheet.write(0,1,'姓名') book.save('stu.xls') #結尾一定要以xls結尾
方法解析
1)book.add_sheet() #在電子表格中創建一個sheet頁,默認單元格覆蓋寫爲False,如果改爲True允許覆蓋寫單元格
def add_sheet(self, sheetname, cell_overwrite_ok=False): """ This method is used to create Worksheets in a Workbook. :param sheetname: The name to use for this sheet, as it will appear in the tabs at the bottom of the Excel application. :param cell_overwrite_ok: If ``True``, cells in the added worksheet will not raise an exception if written to more than once. :return: The :class:`~xlwt.Worksheet.Worksheet` that was added. """
2)sheet.write(r,c,label='') #往單元格寫內容,如果label的默認參數是空,如果不填寫則單元格默認爲空
def write(self, r, c, label="", style=Style.default_style): """ This method is used to write a cell to a :class:`Worksheet`. :param r: The zero-relative number of the row in the worksheet to which the cell should be written. :param c: The zero-relative number of the column in the worksheet to which the cell should be written. :param label: The data value to be written. An :class:`int`, :class:`long`, or :class:`~decimal.Decimal` instance is converted to :class:`float`. A :class:`unicode` instance is written as is. A :class:`bytes` instance is converted to :class:`unicode` using the encoding, which defaults to ``ascii``, specified when the :class:`Workbook` instance was created. A :class:`~datetime.datetime`, :class:`~datetime.date` or :class:`~datetime.time` instance is converted into Excel date format (a float representing the number of days since (typically) ``1899-12-31T00:00:00``, under the pretence that 1900 was a leap year). A :class:`bool` instance will show up as ``TRUE`` or ``FALSE`` in Excel. ``None`` causes the cell to be blank: no data, only formatting. An :class:`xlwt.Formula` instance causes an Excel formula to be written. :param style: A style, also known as an XF (extended format), is an :class:`~xlwt.Style.XFStyle` object, which encapsulates the formatting applied to the cell and its contents. :class:`~xlwt.Style.XFStyle` objects are best set up using the :func:`~xlwt.Style.easyxf` function. They may also be set up by setting attributes in :class:`Alignment`, :class:`Borders`, :class:`Pattern`, :class:`Font` and :class:`Protection` objects then setting those objects and a format string as attributes of an :class:`~xlwt.Style.XFStyle` object. """ self.row(r).write(c, label, style)
3.book.save() #將電子表格保存成一個excel文件
def save(self, filename_or_stream): """ This method is used to save the Workbook to a file in native Excel format. :param filename_or_stream: This can be a string containing a filename of the file, in which case the excel file is saved to disk using the name provided. It can also be a stream object with a write method, such as a :class:`~io.StringIO`, in which case the data for the excel file is written to the stream. """ from . import CompoundDoc doc = CompoundDoc.XlsDoc() doc.save(filename_or_stream, self.get_biff_data())