最新亚洲中文av在线不卡-人妻少妇一区二区三区-青青草无码精品伊人久久-a国产一区二区免费入口-久久www免费人成人片

您好,歡迎訪問通商軟件官方網(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ù)、人資、辦公等一體化管理

本文開放系統(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.libinwudao.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輸出就可以了。

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

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

Scroll to top
咨詢電話
客服郵箱
主站蜘蛛池模板: 99久久免费国产精精品| 婷婷色国产精品视频一区 | 少妇无码av无码专区线| 国产美女在线精品免费观看| 真实国产熟睡乱子伦视频| 国产在线精品一区二区不卡| 中文字幕亚洲综合久久菠萝蜜| 人人超人人超碰超国产97超碰| 中文无码乱人伦中文视频在线| 亚洲欧美日韩综合一区二区 | 亚洲丰满熟女一区二区蜜桃| 欧美成人片一区二区三区| 一本到无码av专区无码| 在厨房被c到高潮a毛片奶水| 99精品人妻少妇一区二区| 亚洲综合久久无码色噜噜赖水| 久久国产精品99国产精| 国产日韩在线亚洲色视频| 中文字幕无码肉感爆乳在线| 东北少妇不戴套对白第一次| 人妻丰满熟妇av无码片| 久久国产精品免费一区下载| 欧美男生射精高潮视频网站| 女人大荫蒂毛茸茸视频| 亚洲精品日韩av专区| 亚洲精品无码久久久久y| 成在人线av无码免费看网站直播 | 亚洲色中文字幕无码av| 麻豆人人妻人人妻人人片av| 中文人妻av久久人妻水蜜桃| 免费的国产成人av网站装睡的| 亚洲日韩av无码一区二区三区人| 亚洲伊人成综合网| 伊人久久婷婷五月综合97色| 免费国产污网站在线观看不要卡| 精品国产偷窥一区二区| 国内精品久久久久影院老司机| 亚洲日韩精品无码专区加勒比海| 国产专业剧情av在线 | 好男人社区影院www| 亚洲色av天天天天天天|