Python uses the XLWT module to manipulate Excel files

Source: Internet
Author: User
Tags save file set background

Export Excel File

1. Use the XLWT module import XLWT

import xlwt # import XLWT

# Create a new Excel file

   file = xlwt. Workbook () #注意这里的Workbook首字母是大写, no words

# Create a new sheet

table = file.add_sheet (' sheet name ')

# Write Data table.write (rows, columns, value)

   Table.write (0,0, ' test ')

# If you repeat the action on a cell, it throws

returns error:   # exception:attempt to overwrite cell:# sheetname=u ' sheet 1 ' rowx=0 colx=0

# so Add Cell_overwrite_ok=true solution when open

table = file.add_sheet (' sheet name ', cell_overwrite_ok=true)

file.save (' Demo.xls ') # Save File

In addition, use the style

style = XLWT. Xfstyle () # Initialize Style

font = XLWT. Font () #为样式创建字体

Font.Name = ' Times New Roman '

Font.Bold = True

Style.font = Font #为样式设置字体

table.write (0, 0, ' Some bold times text ', style) # using Styles

XLWT allows you to format cells or entire rows. You can also add links and formulas. You can read the source code, where there are examples:

dates.py, showing how to set different data formats

hyperlinks.py, showing how to create a hyperlink (Hint:you need to use a formula)

merged.py, show how to merge lattice

row_styles.py, shows how to apply a style to an entire row of squares.

  Example one:

Import XLWT
WBK = XLWT. Workbook ()
Sheet = wbk.add_sheet (' Sheet 1 ')
# indexing is zero based, row and then column
Sheet.write (0,1, ' Test text ')
Sheet.write ("Test text")
Wbk.save (' Test2.xls ') is saved on the desktop by default

Example Two:

Import Stringio
Import XLWT as Excelwrite # Introduction Module

def_make_excel (Self, data_array):if notData_array:return "'# data_array = sorted (data_array, Key=lambda x:x[' Createtime ' ]# Sort by the time of the data #Style_del = Excelwrite.xfstyle () #style_del.alignment.wrap = 1Header= [u'Date of order', u'Departure Time', u'Departure Time', u'Pickup Location', u'Drop off Location', u'Passenger Name', u'Driver Information', u'Port', u'Fleet', u'whether 8 seats', u'Payment Channels', u'Amount Paid', u'Fleet Quote', u'Notes', u'Remark 2', u'Order Origin'] xls= Excelwrite.workbook (style_compression=2) Sheet= Xls.add_sheet ("Sheet1") Sheet.col (3). Width = (30*367) # Set the width of the table Sheet.col (4). Width = (30*367) Sheet.col (5). Width = (20*367) Sheet.col (6). Width = (20*367) Sheet.col (one). Width = (20*367) Sheet.col (). Width = (20*367) I=0#writing a table header forEach_headerinchheader:sheet.write (0, I, each_header) I+ = 1Row= 1
     # Populate data for each row forEach_rowinch data_array: Col=0 # Fills each column of data in a row forEach_colinchHeader:ifEach_colinch(U'Date of order', u'Departure Time'):
# The Self object represents the class itself style=Self._make_date_style () # get style Else: Style=Self._make_normal_style ()ifeach_row['Status'] = = 2: badbg=Excelwrite.pattern () # Set background Badbg.pattern=Badbg.solid_pattern#GreyBadbg.pattern_fore_colour = 23Style.pattern=badbg#Delete LineStyle.font.struck_out =True sheet.write (Row, col, Each_row[each_col], style) Col+ = 1Row+ = 1SF=Stringio.stringio () # Stringio This module can learn the next xls.save (SF) Contents=Sf.getvalue () sf.close ( )returnContents

def_make_normal_style (self): Style_normal=Excelwrite.xfstyle () # Set the style of Excel Style_normal.alignment.wrap= 1returnStyle_normaldef_make_date_style (self): Style_date=Excelwrite.xfstyle () style_date.alignment.wrap= 1Style_date.num_format_str= u'mm month DD Day' returnStyle_date

# The Self object is a derived class that inherits the Tornado.web.RequestHandler
def_send_download (self, file_name, data): Self.set_header ('Content-type','Application/octet-stream') Self.set_header ('content-disposition','attachment; Filename='+file_name) Self.write # writes data back to the Web client self.finish ()

# Call to generate Excel data
Excel_data =self._make_excel (data)ifExcel_data:self._send_download ('1.xls', Excel_data)Else:
Pass

Python uses the XLWT module to manipulate Excel files

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.