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

您好,歡迎訪問通商軟件官方網站!
24小時免費咨詢熱線: 400-1611-009
聯系我們 | 加入合作

Python, 將HTML table 導出Excel

ERP系統 & MES 生產管理系統

10萬用戶實施案例,ERP 系統實現微信、銷售、庫存、生產、財務、人資、辦公等一體化管理

本文開放系統中的一段代碼。將HTML5 table文本導出Excel。

需要的庫

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

目標

網頁上的table部分,只要輸出文本,將html文本輸出成excel。幾乎一摸一樣,可以帶出簡單的css樣式(本文基于bootstrap的標準樣式),合并單元格,表頭等內容。但不能帶出單元格樣式,公式等。

例子

比如上圖。頁面輸出是這個樣子的。

導出后

例子

很簡單吧。

代碼

__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

調用最后一個函數 export_to_xls 就可以了。參數table,是HTML table 字符串。結合django的話,用render_to_string輸出就可以了。

在線疑問仍未解決?專業顧問為您一對一講解

24小時人工在線已服務6865位顧客5分鐘內回復

Scroll to top
咨詢電話
客服郵箱
掃碼咨詢
主站蜘蛛池模板: 91超碰免费在线 | 欧美国产精品一区二区 | 亚洲毛片一区二区三区 | 国产精品成人av性教育 | xxxxxhd亚洲人hd| 密乳av| 精品欧美乱码久久久久久1区2区 | 免费看aaaaa级少淫片 | 精品自拍视频 | 椎名空在线观看 | 国产特级aaaaaa大片 | 日韩三级视频在线播放 | 国产色站 | 免费在线看污视频 | 久国久产久精永久网页 | 亚洲国产中文字幕在线 | 色大师av一区二区三区 | 黄色片小视频 | 午夜精品一区二区三区在线播放 | 日韩欧美中| 久久国产精品精品国产色婷婷 | 国产精品视频自拍 | 天天综合天天做天天综合 | 友田真希一区二区 | www.久久久 | 夜夜草 | 夫妻淫语绿帽对白 | 国产欧美一区二区精品忘忧草 | 雪白的扔子视频大全在线观看 | 国产精品1234区 | 日韩福利在线 | 欧美精品入口蜜桃 | 国产精品区一区二区三 | 欧美激情第三页 | 神秘马戏团在线观看免费高清中文 | 国产精品精 | 精品视频在线观看免费 | 久艹在线视频 | 久久综合狠狠综合久久综合88 | 99热免费在线观看 | 奇米视频在线观看 | 五月天婷婷基地 | 国产福利在线免费观看 | 亚洲欧美另类综合 | 手机看片日韩福利 | 黑人精品一区二区三区 | 人体裸体bbb欣赏 | 欧美精品video | 国产叼嘿视频 | 人妻体内射精一区二区 | 日日狠狠久久偷偷四色综合免费 | 欧美一区亚洲二区 | 借种(出轨高h) | 欧美熟妇乱码在线一区 | 最新av不卡 | 91传媒在线免费观看 | 熊猫成人网 | 中文字幕av免费观看 | 久久久久综合 | 午夜精品一区二区三 | 91涩漫成人官网入口 | 西西毛片 | 欧美日韩一区二区三区不卡视频 | 一级片av | 91福利片| 成人aⅴ视频 | 99激情| 日韩欧美中文在线观看 | 日韩香蕉网 | 丰满少妇在线观看bd | 一级免费在线观看 | 欧美精品网站 | 亚洲av激情无码专区在线播放 | 波多野结衣在线播放视频 | 日本aa视频 | 一级免费看片 | 2021av在线| 人人干人人艹 | 美女免费视频网站 | www.蜜桃av| 日韩精品电影在线 | 浪漫樱花动漫在线观看免费 | 亚洲第一色网 | 免费观看黄色小视频 | 国产视频一区二区三区在线播放 | 新天堂av| 国产成人在线视频播放 | 成人精品久久 | 黄色片免费在线观看 | 免费一区二区视频 | 日韩欧美在线观看一区 | 国精产品一区二区三区 | 国产va在线观看 | www.日韩欧美 | 在线网站av| 欧美激情午夜 | 色综合久久网 | 性生活视屏| 日韩在线播放一区二区 |