久久久国产精品久久久I国产亚洲久一区二区I制服丝袜亚洲I日韩av片在线I久久免费视频8I日韩av在线小说

您好,歡迎訪問(wèn)通商軟件官方網(wǎng)站!
24小時(shí)免費(fèi)咨詢熱線: 400-1611-009
聯(lián)系我們 | 加入合作

Python, 將HTML table 導(dǎo)出Excel

ERP系統(tǒng) & MES 生產(chǎn)管理系統(tǒng)

10萬(wàn)用戶實(shí)施案例,ERP 系統(tǒng)實(shí)現(xiàn)微信、銷售、庫(kù)存、生產(chǎn)、財(cái)務(wù)、人資、辦公等一體化管理

本文開(kāi)放系統(tǒng)中的一段代碼。將HTML5 table文本導(dǎo)出Excel。

需要的庫(kù)

  • python 2.7/2.x
  • xlwt
  • Django(可選)

目標(biāo)

網(wǎng)頁(yè)上的table部分,只要輸出文本,將html文本輸出成excel。幾乎一摸一樣,可以帶出簡(jiǎn)單的css樣式(本文基于bootstrap的標(biāo)準(zhǔn)樣式),合并單元格,表頭等內(nèi)容。但不能帶出單元格樣式,公式等。

例子

比如上圖。頁(yè)面輸出是這個(gè)樣子的。

導(dǎo)出后

例子

很簡(jiǎn)單吧。

代碼

__author__ = 'www.uzefa.com'

from django.http import HttpResponse
from django.utils.http import urlquote
import xlwt, HTMLParser, StringIO, uuid

blue_stype = xlwt.easyxf('alignment: horz left, vert top; pattern: pattern solid, fore_colour light_blue; font: bold on;')
red_stype = xlwt.easyxf('alignment: horz left, vert top; pattern: pattern solid, fore_colour red; font: bold on;')
green_stype = xlwt.easyxf('alignment: horz left, vert top; pattern: pattern solid, fore_colour light_green; font: bold on;')
yellow_stype = xlwt.easyxf('alignment: horz left, vert top; pattern: pattern solid, fore_colour light_yellow; font: bold on;')
orange_stype = xlwt.easyxf('alignment: horz left, vert top; pattern: pattern solid, fore_colour light_orange; font: bold on;')
merge_stype = xlwt.easyxf('alignment: wrap on;')

bold_stype = xlwt.easyxf('alignment: horz left, vert top; font: bold on;')
mydefault_stype = xlwt.easyxf('alignment: horz left, vert top')

STAG = 'stag'
ETAG = 'etag'
DATA = 'data'

def html_table_to_excel(table):
    """ html_table_to_excel(table): Takes an HTML table of data and formats it so that it can be inserted into an Excel Spreadsheet.
    """
    table_ls = []

    class MyHTMLParser(HTMLParser.HTMLParser):
        '''
        parser
        '''

        def handle_starttag(self, tag, attrs):
            table_ls.append((STAG, tag, attrs))

        def handle_endtag(self, tag):
            table_ls.append((ETAG, tag, None))

        def handle_data(self, contentstr):
            table_ls.append((DATA, contentstr.strip(), None))

    p = MyHTMLParser()
    p.feed(table)

    return table_ls

def export_to_sheet(wb, sheet_title, table_str):
    '''
    sheet
    '''
    ws = wb.add_sheet(sheet_title)

    ls = html_table_to_excel(table_str)

    xstatus = ''
    cline = 0
    ccell = 0
    b_readyinsert = False
    xattrs = None
    xcontent = ''
    cells_occupy = set()

    for tag, content, attrs in ls:
        if tag == STAG and content == 'thead':
            xstatus = 'thead'
        elif tag == ETAG and content == 'thead':
            xstatus = ''
        if tag == STAG and content == 'tbody':
            xstatus = 'tbody'
        elif tag == ETAG and content == 'tbody':
            xstatus = ''

        elif tag == STAG and content == 'tr':
            # row go
            ccell = 0
        elif tag == ETAG and content == 'tr':
            # row go
            cline += 1

        elif tag == STAG and content in ['td', 'th']:
            b_readyinsert = True
            xcontent = ''
            xattrs = dict(attrs)
        elif tag == ETAG and content in ['td', 'th']:
            # fill cell
            xstyle = mydefault_stype
            if 'class' in xattrs:
                xattr_class = xattrs['class']
                if 'success' in xattr_class:
                    xstyle = green_stype
                elif 'warning' in xattr_class:
                    xstyle = yellow_stype
                elif 'danger' in xattr_class:
                    xstyle = red_stype
                elif 'info' in xattr_class:
                    xstyle = blue_stype
            if not xstyle:
                xstyle = xstatus == 'thead' and bold_stype or mydefault_stype

            # test occupy
            while (cline, ccell) in cells_occupy:
                ccell += 1

            if 'colspan' in xattrs and 'rowspan' in xattrs:
                rowspan = int(xattrs['rowspan'])
                colspan = int(xattrs['colspan'])
                ws.write_merge(cline, rowspan - 1 + cline, ccell, colspan - 1 + ccell, xcontent, xstyle)
                for x in range(0, rowspan):
                    cells_occupy.add((cline + x, ccell))
                for x in range(0, colspan):
                    cells_occupy.add((cline, ccell + x))
            elif 'rowspan' in xattrs:
                rowspan = int(xattrs['rowspan'])
                ws.write_merge(cline, rowspan - 1 + cline, ccell, ccell, xcontent, xstyle)
                for x in range(0, rowspan):
                    cells_occupy.add((cline + x, ccell))
            elif 'colspan' in xattrs:
                colspan = int(xattrs['colspan'])
                ws.write_merge(cline, cline, ccell, colspan - 1 + ccell, xcontent, xstyle)
                for x in range(0, colspan):
                    cells_occupy.add((cline, ccell + x))
            else:
                ws.write(cline, ccell, xcontent, xstyle)
                cells_occupy.add((cline, ccell))

            b_readyinsert = False
            xattrs = {}
            xstyle = None
            # cell go
            # ccell += 1

        elif b_readyinsert:
            if content == 'br':
                if xcontent:
                    xcontent += 'r'

            elif tag == DATA:
                content = content.strip()
                if content:
                    if xcontent:
                        xcontent += ' ' + content
                    else:
                        xcontent = content

    return wb

def export_to_xls(table, b_export_response=True, table_title=''):
    """
    @param  table:              string or dict
    """
    wb = xlwt.Workbook(style_compression=2)
    if isinstance(table, dict):
        if table:
            vx = ''
            for kt, v in table.items():
                export_to_sheet(wb, unicode(kt), v)
        else:
            wb.add_sheet('EMPTY')
    elif isinstance(table, list):
        if table:
            vx = ''
            for kt, v in table:
                vx += u'<table><thead><tr><th></th></tr><tr><th>{}</th></tr></thead></table>{}'.format(unicode(kt), v)
            export_to_sheet(wb, 'NEW', vx)
        else:
            wb.add_sheet('EMPTY')
    else:
        export_to_sheet(wb, 'NEW', table)

    if b_export_response:
        sio = StringIO.StringIO()
        wb.save(sio)
        dd = sio.getvalue()
        sio.close()

        #download
        response = HttpResponse(dd, content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename={0}.xls'.format(urlquote(table_title) or str(uuid.uuid4()))
        return response

    else:
        return wb

調(diào)用最后一個(gè)函數(shù) export_to_xls 就可以了。參數(shù)table,是HTML table 字符串。結(jié)合django的話,用render_to_string輸出就可以了。

在線疑問(wèn)仍未解決?專業(yè)顧問(wèn)為您一對(duì)一講解

24小時(shí)人工在線已服務(wù)6865位顧客5分鐘內(nèi)回復(fù)

Scroll to top
咨詢電話
客服郵箱
掃碼咨詢
主站蜘蛛池模板: 蜜臀av一区二区三区有限公司 | 99久久久无码国产精品免费 | 五月婷婷一区 | 884aa四虎影成人精品一区 | 国产 欧美 自拍 | 乱日视频 | 亚洲熟女乱色综合亚洲av | 国内外成人在线视频 | 久久综合热| 天堂va蜜桃一区二区三区漫画版 | 日爽夜爽 | 欧美精品999 | 日本乱子伦 | 日韩免费大片 | 亚洲欧美日韩精品久久 | 成都4电影免费高清 | 久久伊| 妖精视频一区二区 | 日韩精品电影网 | 色视频免费观看 | 一本一道久久a久久 | 久久香蕉影院 | 夫妻自拍偷拍 | 香蕉视频2020 | 精品视频久久久久 | 丁香六月天婷婷 | 华丽的外出在线观看 | 欧美日韩一区二区三区在线电影 | 国产精品一区久久 | 国产亚洲精品女人久久久久久 | 全部孕妇毛片丰满孕妇孕交 | 国产在线视频网址 | 国产91在线观看丝袜 | 亚洲啊v | 紧身裙女教师三上悠亚红杏 | 精品国产乱码久久久久久牛牛 | 色小姐av | 国产成人精品aa毛片 | 亚洲黄站 | 色屋视频| 一级二级三级黄色片 | 一区二区av在线 | 四虎久久久 | 久爱视频在线观看 | 在线观看的av网址 | 中文字幕在线影院 | 国产成人一区二区三区免费看 | 亚洲1234区| 久久免费的精品国产v∧ | 久在线视频 | 婷婷激情六月 | 99国内精品 | 超碰97人人在线 | 偷自在线 | 久草新在线| 97超碰人人爱 | 国产懂色av| 国产精品尤物视频 | 久久全国免费视频 | 日本va在线观看 | 国产女人和拘做受视频免费 | 欧美粗暴jizz性欧美20 | 操处女逼视频 | 欧美另类极品videosbest使用方法 | 亚洲天堂福利 | 日日骚av一区二区 | 国产情侣在线视频 | 久草视频福利在线 | 国产在线观看无码免费视频 | 交做爰xxxⅹ性爽 | 免费荫蒂添的好舒服视频 | 色优久久 | 动漫美女被艹 | 欧美精品videosex极品 | 99看片 | 日韩中文字幕在线免费观看 | 日本激情在线 | 青青插| 男男大尺度 | 成人欧美一区二区三区黑人动态图 | 欧美在线视频免费播放 | 我把护士日出水了视频90分钟 | 亚洲羞羞 | 中文字幕在线观看欧美 | 另类第一页 | 91丝袜国产在线观看 | 经典毛片| 欧美国产在线视频 | 欧美揉bbbbb揉bbbbb | 第一页综合 | 国产白拍 | 久久大胆视频 | 丁香九月婷婷 | va在线| 午夜视频www | 亚洲女成人图区 | 亚洲综合a| 欧美日韩国产精品成人 | 成人福利影院 |