Python xlwt.XFStyle() Examples

The following are 30 code examples of xlwt.XFStyle(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xlwt , or try the search function .
Example #1
Source File: mytools.py    From chat with MIT License 7 votes vote down vote up
def set_excel_style(name, height, bold=False):
    """Set excel style.
    """
    style = xlwt.XFStyle() # 初始化样式
    font = xlwt.Font() # 为样式创建字体
    font.name = name # 例如'Times New Roman'
    font.bold = bold
    font.color_index = 4
    font.height = height
    if bold:
        borders = xlwt.Borders()
        borders.left = 6
        borders.right = 6
        borders.top = 6
        borders.bottom = 6
        style.borders = borders
    style.font = font
    return style 
Example #2
Source File: db_excel.py    From nlp_learning with MIT License 7 votes vote down vote up
def set_style(name, height, bold=False):
    # 设置字体
    style = xlwt.XFStyle()
    font = xlwt.Font()
    font.name = name
    font.bold = bold
    font.color_index = 4
    font.height = height
    style.font = font
    # 设置边框
    borders = xlwt.Borders()
    # 细实线:1,小粗实线:2,细虚线:3,中细虚线:4,大粗实线:5,双线:6,细点虚线:7
    # 大粗虚线:8,细点划线:9,粗点划线:10,细双点划线:11,粗双点划线:12,斜点划线:13
    borders.left = 1
    borders.right = 1
    borders.top = 1
    borders.bottom = 1
    style.borders = borders

    return style


# 写Excel 
Example #3
Source File: AnalysisData.py    From UniversityRecruitment-sSurvey with Apache License 2.0 7 votes vote down vote up
def set_style(name, height, bold=False):
    style = xlwt.XFStyle()  # 初始化样式

    font = xlwt.Font()  # 为样式创建字体
    font.name = name  # 'Times New Roman'
    font.bold = bold
    font.color_index = 4
    font.height = height

    # borders= xlwt.Borders()
    # borders.left= 6
    # borders.right= 6
    # borders.top= 6
    # borders.bottom= 6

    style.font = font
    # style.borders = borders

    return style 
Example #4
Source File: test_simple.py    From InternationalizationScript-iOS with MIT License 6 votes vote down vote up
def create_simple_xls(self, **kw):
        font0 = xlwt.Font()
        font0.name = 'Times New Roman'
        font0.colour_index = 2
        font0.bold = True

        style0 = xlwt.XFStyle()
        style0.font = font0

        style1 = xlwt.XFStyle()
        style1.num_format_str = 'D-MMM-YY'

        wb = xlwt.Workbook(**kw)
        ws = wb.add_sheet('A Test Sheet')

        ws.write(0, 0, 'Test', style0)
        ws.write(1, 0, datetime(2010, 12, 5), style1)
        ws.write(2, 0, 1)
        ws.write(2, 1, 1)
        ws.write(2, 2, xlwt.Formula("A3+B3"))
        return wb, ws 
Example #5
Source File: lptxls.py    From lpts with GNU General Public License v2.0 6 votes vote down vote up
def data_title_style():
    style = xlwt.XFStyle()
    style.font = base_xls.font(bold=True, colour=0x0C)
    style.alignment = base_xls.alignment()
    style.borders = base_xls.borders(line=0x01)
    style.pattern = base_xls.pattern(solid_pattern=0x01, fore_colour=0x29)
    return style 
Example #6
Source File: excel.py    From elasticintel with GNU General Public License v3.0 6 votes vote down vote up
def _convert_to_style(cls, style_dict, num_format_str=None):
        """
        converts a style_dict to an xlwt style object
        Parameters
        ----------
        style_dict: style dictionary to convert
        num_format_str: optional number format string
        """
        import xlwt

        if style_dict:
            xlwt_stylestr = cls._style_to_xlwt(style_dict)
            style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
        else:
            style = xlwt.XFStyle()
        if num_format_str is not None:
            style.num_format_str = num_format_str

        return style 
Example #7
Source File: excel.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def _convert_to_style(cls, style_dict, num_format_str=None):
        """
        converts a style_dict to an xlwt style object
        Parameters
        ----------
        style_dict: style dictionary to convert
        num_format_str: optional number format string
        """
        import xlwt

        if style_dict:
            xlwt_stylestr = cls._style_to_xlwt(style_dict)
            style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
        else:
            style = xlwt.XFStyle()
        if num_format_str is not None:
            style.num_format_str = num_format_str

        return style 
Example #8
Source File: test_simple.py    From InternationalizationScript-iOS with MIT License 6 votes vote down vote up
def create_simple_xls(self, **kw):
        font0 = xlwt.Font()
        font0.name = 'Times New Roman'
        font0.colour_index = 2
        font0.bold = True

        style0 = xlwt.XFStyle()
        style0.font = font0

        style1 = xlwt.XFStyle()
        style1.num_format_str = 'D-MMM-YY'

        wb = xlwt.Workbook(**kw)
        ws = wb.add_sheet('A Test Sheet')

        ws.write(0, 0, 'Test', style0)
        ws.write(1, 0, datetime(2010, 12, 5), style1)
        ws.write(2, 0, 1)
        ws.write(2, 1, 1)
        ws.write(2, 2, xlwt.Formula("A3+B3"))
        return wb, ws 
Example #9
Source File: GetPageDetail.py    From CNKI-download with MIT License 6 votes vote down vote up
def set_style(self):
        '''
        设置excel样式
        '''
        self.sheet.col(1).width = 256 * 30
        self.sheet.col(2).width = 256 * 15
        self.sheet.col(3).width = 256 * 20
        self.sheet.col(4).width = 256 * 20
        self.sheet.col(5).width = 256 * 60
        self.sheet.col(6).width = 256 * 15
        self.sheet.col(9).width = 256 * 15
        self.sheet.row(0).height_mismatch = True
        self.sheet.row(0).height = 20 * 20
        self.basic_style = xlwt.XFStyle()
        al = xlwt.Alignment()
        # 垂直对齐
        al.horz = al.HORZ_CENTER
        # 水平对齐
        al.vert = al.VERT_CENTER
        # 换行
        al.wrap = al.WRAP_AT_RIGHT
        # 设置边框
        borders = xlwt.Borders()
        borders.left = 6
        borders.right = 6
        borders.top = 6
        borders.bottom = 6

        self.basic_style.alignment = al
        self.basic_style.borders = borders 
Example #10
Source File: pump.py    From pychemqt with GNU General Public License v3.0 6 votes vote down vote up
def export2xls(self):
        import xlwt
        font0 = xlwt.Font()
        font0.bold = True
        font0.height = 300
        print((font0.height))

        style0 = xlwt.XFStyle()
        style0.font = font0

        style1 = xlwt.XFStyle()
        style1.num_format_str = 'D-MMM-YY'

        wb = xlwt.Workbook()
        ws = wb.add_sheet('A Test Sheet')

        ws.write(0, 0, 'Test', style0)
        ws.write(2, 0, 1)
        ws.write(2, 1, 1)
        ws.write(2, 2, xlwt.Formula("A3+B3"))

        wb.save('datasheet.xls')
        os.system("gnumeric datasheet.xls") 
Example #11
Source File: excel.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def _convert_to_style(cls, style_dict, num_format_str=None):
        """
        converts a style_dict to an xlwt style object
        Parameters
        ----------
        style_dict : style dictionary to convert
        num_format_str : optional number format string
        """
        import xlwt

        if style_dict:
            xlwt_stylestr = cls._style_to_xlwt(style_dict)
            style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
        else:
            style = xlwt.XFStyle()
        if num_format_str is not None:
            style.num_format_str = num_format_str

        return style 
Example #12
Source File: excel.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _convert_to_style(cls, style_dict, num_format_str=None):
        """
        converts a style_dict to an xlwt style object
        Parameters
        ----------
        style_dict : style dictionary to convert
        num_format_str : optional number format string
        """
        import xlwt

        if style_dict:
            xlwt_stylestr = cls._style_to_xlwt(style_dict)
            style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
        else:
            style = xlwt.XFStyle()
        if num_format_str is not None:
            style.num_format_str = num_format_str

        return style 
Example #13
Source File: exceltools.py    From Computable with MIT License 6 votes vote down vote up
def xlformat_factory(format):
    """
    copy the format, perform any overrides, and attach an xlstyle instance
    copied format is returned
    """

    #if we have created an excel format already using this format,
    #don't recreate it; mlab.FormatObj override has to make objs with
    #the same props hash to the same value
    key = hash(format)
    fmt_ = xlformat_factory.created_formats.get(key)
    if fmt_ is not None:
        return fmt_

    format = copy.deepcopy(format)

    xlstyle = excel.XFStyle()
    if isinstance(format, mlab.FormatPercent):
       zeros = ''.join(['0']*format.precision)
       xlstyle.num_format_str = '0.%s%%;[RED]-0.%s%%'%(zeros, zeros)
       format.scale = 1.
    elif isinstance(format, mlab.FormatFloat):
        if format.precision>0:
            zeros = ''.join(['0']*format.precision)
            xlstyle.num_format_str = '#,##0.%s;[RED]-#,##0.%s'%(zeros, zeros)
        else:
            xlstyle.num_format_str = '#,##;[RED]-#,##'
    elif isinstance(format, mlab.FormatInt):
        xlstyle.num_format_str = '#,##;[RED]-#,##'
    else:
        xlstyle = None

    format.xlstyle = xlstyle

    xlformat_factory.created_formats[ key ] = format

    return format 
Example #14
Source File: excel.py    From Computable with MIT License 6 votes vote down vote up
def _convert_to_style(cls, style_dict, num_format_str=None):
        """
        converts a style_dict to an xlwt style object
        Parameters
        ----------
        style_dict: style dictionary to convert
        num_format_str: optional number format string
        """
        import xlwt

        if style_dict:
            xlwt_stylestr = cls._style_to_xlwt(style_dict)
            style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
        else:
            style = xlwt.XFStyle()
        if num_format_str is not None:
            style.num_format_str = num_format_str

        return style 
Example #15
Source File: excel.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _convert_to_style(cls, style_dict, num_format_str=None):
        """
        converts a style_dict to an xlwt style object
        Parameters
        ----------
        style_dict: style dictionary to convert
        num_format_str: optional number format string
        """
        import xlwt

        if style_dict:
            xlwt_stylestr = cls._style_to_xlwt(style_dict)
            style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
        else:
            style = xlwt.XFStyle()
        if num_format_str is not None:
            style.num_format_str = num_format_str

        return style 
Example #16
Source File: views.py    From devops with GNU General Public License v3.0 5 votes vote down vote up
def export(request):
    if request.method == "GET":
        asset_list = models.Assets.objects.all()
        bt = ['ID','主机名','外网地址','内网地址','系统类型','机房','ServerID','GameID','角色','创建时间','更新时间','是否启用','备注']
        wb = xlwt.Workbook(encoding='utf-8')
        sh = wb.add_sheet("主机详情",cell_overwrite_ok=True)
        dateFormat = xlwt.XFStyle()
        dateFormat.num_format_str = 'yyyy/mm/dd'
        for i in range(len(bt)):
            sh.write(0,i,bt[i])
        for i in range(len(asset_list)):
            sh.write(i + 1, 0, asset_list[i].id)
            sh.write(i + 1, 1, asset_list[i].hostname)
            sh.write(i + 1, 2, asset_list[i].wip)
            sh.write(i + 1, 3, asset_list[i].lip)
            sh.write(i + 1, 4, asset_list[i].system_type)
            for idc in asset_list[i].idc_set.all():
                sh.write(i + 1, 5, idc.name)
            sh.write(i + 1, 6, asset_list[i].serverid)
            sh.write(i + 1, 7, asset_list[i].gameid)
            for g in asset_list[i].hostgroup_set.all():
                sh.write(i + 1, 8, g.name)
            sh.write(i + 1, 9, asset_list[i].ctime,dateFormat)
            sh.write(i + 1, 10, asset_list[i].utime,dateFormat)
            sh.write(i + 1, 11, asset_list[i].get_online_status_display())
            sh.write(i + 1, 12, asset_list[i].memo)
        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=asset' + time.strftime('%Y%m%d', time.localtime(
                time.time())) + '.xls'
        wb.save(response)

        return response 
Example #17
Source File: lptxls.py    From lpts with GNU General Public License v2.0 5 votes vote down vote up
def section_title_style():
    style = xlwt.XFStyle()
    style.font = base_xls.font(bold=True, colour=0x30, height=0x00EE)
    style.alignment = base_xls.alignment()
    style.borders = base_xls.borders(line=0x01)
    style.pattern = base_xls.pattern(solid_pattern=0x00, fore_colour=0x2A)
    return style 
Example #18
Source File: lptxls.py    From lpts with GNU General Public License v2.0 5 votes vote down vote up
def data_seq_style(font_colour=0x08):
    style = xlwt.XFStyle()
    style.font = base_xls.font(bold=True, colour=font_colour)
    style.alignment = base_xls.alignment()
    style.borders = base_xls.borders(line=0x01)
    style.pattern = base_xls.pattern(solid_pattern=0x01, fore_colour=0x2A)
    return style 
Example #19
Source File: lptxls.py    From lpts with GNU General Public License v2.0 5 votes vote down vote up
def description_style():
    style = xlwt.XFStyle()
    style.font = base_xls.font(bold=True, colour=0x11)
    style.alignment = base_xls.alignment(inde=0)
    style.alignment.wrap = 1
    style.borders = base_xls.borders(line=0x01)
    style.pattern = base_xls.pattern(solid_pattern=0x00, fore_colour=0x16)
    return style 
Example #20
Source File: lptxls.py    From lpts with GNU General Public License v2.0 5 votes vote down vote up
def title_style():
    '''
    '''
    style = xlwt.XFStyle()
    style.font = base_xls.font(bold=True, colour=0x0A)
    style.alignment = base_xls.alignment(horz=0x02)
    style.borders = base_xls.borders(line=0x01)
    style.pattern = base_xls.pattern(solid_pattern=0x01, fore_colour=0x1F)
    return style 
Example #21
Source File: lptxls.py    From lpts with GNU General Public License v2.0 5 votes vote down vote up
def info_style():
    '''
    '''
    style = xlwt.XFStyle()
    style.font = base_xls.font(bold=True, colour=0x08)
    style.alignment = base_xls.alignment()
    style.alignment.wrap = 1
    style.borders = base_xls.borders(line=0x01)
    style.pattern = base_xls.pattern(solid_pattern=0x00, fore_colour=0x2A)
    return style 
Example #22
Source File: lptxls.py    From lpts with GNU General Public License v2.0 5 votes vote down vote up
def cell_style():
    '''
    '''
    style = xlwt.XFStyle()
    style.font = base_xls.font(bold=True, colour=0x08)
    style.alignment = base_xls.alignment(horz=0x01)
    style.borders = base_xls.borders(line=0x01)
    style.pattern = base_xls.pattern(solid_pattern=0x01, fore_colour=0x2B)
    return style 
Example #23
Source File: funda_rotation.py    From stockbot with GNU General Public License v2.0 5 votes vote down vote up
def build_result(self, coupon_descr_list):
        stk_wb = xlwt.Workbook()
        myfont = xlwt.Font()
        mystyle = xlwt.XFStyle()
        mystyle.font = myfont
        sheet_name = str(date.today())
        sheet = stk_wb.add_sheet(sheet_name, cell_overwrite_ok=True)

        for index, item in enumerate(coupon_descr_list):
            self._write_decision_data(item, index*5, sheet)
            self._write_selected_data(item, index*5, sheet)

        stk_wb.save('../output/funda_rotation_{}'.format(sheet_name) + '.xls') 
Example #24
Source File: views.py    From django-experience with MIT License 5 votes vote down vote up
def export_users_xls(request):
    response = HttpResponse(content_type='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename="customers.xls"'

    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('Customers')

    # Sheet header, first row
    row_num = 0

    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    columns = ['Nome', 'Sobrenome', 'E-mail', 'Nascimento', 'Criado em']

    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)

    # Sheet body, remaining rows
    default_style = xlwt.XFStyle()

    rows = Customer.objects.all().values_list('first_name',
                                              'last_name',
                                              'email',
                                              'birthday',
                                              'created')
    for row, rowdata in enumerate(rows):
        row_num += 1
        for col, val in enumerate(rowdata):
            if isinstance(val, datetime):
                val = val.strftime('%d/%m/%Y %H:%M')
            elif isinstance(val, date):
                val = val.strftime('%d/%m/%Y')
            ws.write(row_num, col, val, default_style)

    wb.save(response)
    return response 
Example #25
Source File: exceltools.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def xlformat_factory(format):
    """
    copy the format, perform any overrides, and attach an xlstyle instance
    copied format is returned
    """

    #if we have created an excel format already using this format,
    #don't recreate it; mlab.FormatObj override has to make objs with
    #the same props hash to the same value
    key = hash(format)
    fmt_ = xlformat_factory.created_formats.get(key)
    if fmt_ is not None:
        return fmt_

    format = copy.deepcopy(format)

    xlstyle = excel.XFStyle()
    if isinstance(format, mlab.FormatPercent):
       zeros = ''.join(['0']*format.precision)
       xlstyle.num_format_str = '0.%s%%;[RED]-0.%s%%'%(zeros, zeros)
       format.scale = 1.
    elif isinstance(format, mlab.FormatFloat):
        if format.precision>0:
            zeros = ''.join(['0']*format.precision)
            xlstyle.num_format_str = '#,##0.%s;[RED]-#,##0.%s'%(zeros, zeros)
        else:
            xlstyle.num_format_str = '#,##;[RED]-#,##'
    elif isinstance(format, mlab.FormatInt):
        xlstyle.num_format_str = '#,##;[RED]-#,##'
    else:
        xlstyle = None

    format.xlstyle = xlstyle

    xlformat_factory.created_formats[ key ] = format

    return format 
Example #26
Source File: reports.py    From jorvik with GNU General Public License v3.0 4 votes vote down vote up
def generate(self):
        COLUMNS = ['Turno', 'Inizio', 'Fine', 'Partecipanti']
        DATE_FORMAT = '%d/%m/%Y %I:%M'

        wb = xlwt.Workbook(encoding='utf-8')
        ws = wb.add_sheet(self.attivita.nome)

        row_num = 0

        ordered_columns = {i: line for line, i in enumerate(COLUMNS)}
        # Patch for py3.5: remember dict order
        ordered_columns = OrderedDict(sorted(ordered_columns.items(), key=lambda x: x[1]))
        columns = list(ordered_columns.keys())

        style = xlwt.XFStyle()
        style.alignment.wrap = 1

        for col_num in range(len(columns)):
            ws.write(row_num, col_num, columns[col_num])

        for turno, partecipanti in self.turni_e_partecipanti:
            row_num += 1

            inizio, fine = turno.inizio.strftime(DATE_FORMAT), turno.fine.strftime(DATE_FORMAT)

            ws.write(row_num, ordered_columns['Turno'], turno.nome)
            ws.write(row_num, ordered_columns['Inizio'], inizio)
            ws.write(row_num, ordered_columns['Fine'], fine)

            partecipanti_cell = list()
            for partecipante in partecipanti:
                partecipanti_cell.append("%s - %s" % (
                    partecipante.codice_fiscale,
                    partecipante.nome_completo
                ))

            partecipanti_cell = partecipanti_cell if partecipanti_cell else ["Nessun partecipante registrato.",]

            ws.write(row_num, ordered_columns['Partecipanti'],
                '\n'.join(partecipanti_cell),
                style
            )

            ws.col(ordered_columns['Turno']).width = int((len(turno.nome)*1)*260)
            ws.col(ordered_columns['Inizio']).width = int(len(inizio)*260)
            ws.col(ordered_columns['Fine']).width = int(len(fine)*260)
            ws.col(ordered_columns['Partecipanti']).width = int(45*260)
            ws.row(row_num).height_mismatch = True
            ws.row(row_num).height = 300 * len(partecipanti_cell)

        return wb 
Example #27
Source File: views.py    From autoops with Apache License 2.0 4 votes vote down vote up
def export(request):
    if request.method == "GET":
        a = asset.objects.all()

        bt = ['主机名', '外网IP', '管理IP', '内网IP', 'ssh端口', '型号', '系统版本', "网卡1mac地址", "网卡2mac地址", "网卡3mac地址", "网卡4mac地址",
              '登陆用户', '数据中心', '机柜', '位置', '序列号', 'CPU', '内存', "硬盘", "上联端口", "出厂时间", "到保时间", '产品线', '是否启用', "备注"
            , '创建时间', '更新时间', ]

        wb = xlwt.Workbook(encoding='utf-8')
        sh = wb.add_sheet("详情")

        dateFormat = xlwt.XFStyle()
        dateFormat.num_format_str = 'yyyy/mm/dd'

        for i in range(len(bt)):
            sh.write(0, i, bt[i])

        for i in range(len(a)):
            sh.write(i + 1, 0, a[i].hostname)
            sh.write(i + 1, 1, a[i].network_ip)
            sh.write(i + 1, 2, a[i].manage_ip)
            sh.write(i + 1, 3, a[i].inner_ip)
            sh.write(i + 1, 4, a[i].port)
            sh.write(i + 1, 5, a[i].model)
            sh.write(i + 1, 6, a[i].system)
            sh.write(i + 1, 7, a[i].eth0)
            sh.write(i + 1, 8, a[i].eth1)
            sh.write(i + 1, 9, a[i].eth2)
            sh.write(i + 1, 10, a[i].eth3)
            sh.write(i + 1, 11, a[i].system_user.name)
            sh.write(i + 1, 12, a[i].data_center.data_center_list)
            sh.write(i + 1, 13, a[i].cabinet)
            sh.write(i + 1, 14, a[i].position)
            sh.write(i + 1, 15, a[i].sn)
            sh.write(i + 1, 16, a[i].cpu)
            sh.write(i + 1, 17, a[i].memory)
            sh.write(i + 1, 18, a[i].disk)
            sh.write(i + 1, 19, a[i].uplink_port)
            sh.write(i + 1, 20, a[i].ship_time, dateFormat)
            sh.write(i + 1, 21, a[i].end_time, dateFormat)
            sh.write(i + 1, 22, a[i].product_line.name)
            sh.write(i + 1, 23, a[i].is_active)
            sh.write(i + 1, 24, a[i].ps)
            sh.write(i + 1, 25, a[i].ctime, dateFormat)
            sh.write(i + 1, 26, a[i].utime, dateFormat)

        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment; filename=asset' + time.strftime('%Y%m%d', time.localtime(
            time.time())) + '.xls'
        wb.save(response)

        return response 
Example #28
Source File: ODYM_Classes.py    From ODYM with MIT License 4 votes vote down vote up
def SankeyExport(self,Year, Path, Element): # Export data for given year in excel format for the D3.js Circular Sankey method
        """ Exports MFAsystem to xls Template for the Circular Sankey method."""
        
        TimeIndex = Year - self.Time_Start
        
        myfont = xlwt.Font()
        myfont.bold = True
        mystyle = xlwt.XFStyle()
        mystyle.font = myfont
        
        Result_workbook  = xlwt.Workbook(encoding = 'ascii') 
        Result_worksheet = Result_workbook.add_sheet('Nodes') 
        Result_worksheet.write(0, 0, label = 'Name', style = mystyle)
        Result_worksheet.write(0, 1, label = 'Color', style = mystyle)
        Result_worksheet.write(0, 2, label = 'Orientation', style = mystyle)
        Result_worksheet.write(0, 3, label = 'Width', style = mystyle)
        Result_worksheet.write(0, 4, label = 'Height', style = mystyle)
        Result_worksheet.write(0, 5, label = 'x_position', style = mystyle)
        Result_worksheet.write(0, 6, label = 'y_position', style = mystyle)
        
        for m in range(0,len(self.ProcessList)): 
            if self.ProcessList[m].Graphical is None:
                raise ValueError('Graphical properties of process number {foo} are not set. No export to Sankey possible, as position of process on canvas etc. needs is not specified.'.format(foo = m))
            Result_worksheet.write(m +1, 0, label = self.ProcessList[m].Graphical['Name'])
            Result_worksheet.write(m +1, 1, label = self.ProcessList[m].Graphical['Color'])
            Result_worksheet.write(m +1, 2, label = self.ProcessList[m].Graphical['Angle'])
            Result_worksheet.write(m +1, 3, label = self.ProcessList[m].Graphical['Width'])
            Result_worksheet.write(m +1, 4, label = self.ProcessList[m].Graphical['Height'])
            Result_worksheet.write(m +1, 5, label = self.ProcessList[m].Graphical['xPos'])
            Result_worksheet.write(m +1, 6, label = self.ProcessList[m].Graphical['yPos'])
            
        Result_worksheet = Result_workbook.add_sheet('Flows') 
        Result_worksheet.write(0, 0, label = 'StartNode', style = mystyle)
        Result_worksheet.write(0, 1, label = 'EndNode', style = mystyle)
        Result_worksheet.write(0, 2, label = 'Value', style = mystyle)
        Result_worksheet.write(0, 3, label = 'Color', style = mystyle)
        
        for key in self.FlowDict:
            Result_worksheet.write(m +1, 0, label = self.FlowDict[key].P_Start)
            Result_worksheet.write(m +1, 1, label = self.FlowDict[key].P_End)
            Result_worksheet.write(m +1, 2, label = float(self.Flow_Sum_By_Element(key)[TimeIndex,Element]))
            Result_worksheet.write(m +1, 3, label = self.FlowDict[key].Color)
            
        Result_workbook.save(Path + self.Name + '_' + str(TimeIndex) + '_' + str(Element) + '_Sankey.xls') 
Example #29
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def get(self, *args, **kwargs):
        project=get_object_or_404(Project, pk=self.kwargs.get('pk'))
        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename="bulk_upload_sites.xls"'
        wb = xlwt.Workbook(encoding='utf-8')
        ws = wb.add_sheet('Sites')
        # Sheet header, first row
        row_num = 0
        font_style = xlwt.XFStyle()
        font_style.font.bold = True
        columns = ['identifier', 'name', 'type', 'phone', 'address', 'public_desc', 'additional_desc', 'latitude',
                   'longitude', ]
        if project.cluster_sites:
            columns += ['region_id', ]
        meta_ques = project.site_meta_attributes
        for question in meta_ques:
            columns += [question['question_name']]
        for col_num in range(len(columns)):
            ws.write(row_num, col_num, columns[col_num], font_style)
        row_num += 1

        font_style_unbold = xlwt.XFStyle()
        font_style_unbold.font.bold = False
        region_id = self.kwargs.get('region_id', None)
        sites = project.sites.all().order_by('identifier')

        if region_id:
            if region_id == "0":
                sites = project.sites.filter(region_id=None).order_by('identifier')
            else:
                sites = project.sites.filter(region_id=region_id).order_by('identifier')
        
        for site in sites:
            
            columns = [site.identifier, site.name, site.type.identifier if site.type else "", site.phone, site.address, site.public_desc, site.additional_desc, site.latitude,
                       site.longitude, ]
            
            if project.cluster_sites:
                if site.region:
                    columns += [site.region.identifier, ]
                else:
                    columns += ['', ]
            meta_ques = project.site_meta_attributes
            meta_ans = site.site_meta_attributes_ans
            for question in meta_ques:
                if question['question_name'] in meta_ans:
                    columns += [meta_ans[question['question_name']]]
                else:
                    columns += ['']
            for col_num in range(len(columns)):
                ws.write(row_num, col_num, columns[col_num], font_style_unbold)
            row_num += 1
        wb.save(response)
        return response 
Example #30
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def get(self, request, pk, edit=0):
        source_user = self.request.user   
        project = get_object_or_404(Project, pk=self.kwargs.get('pk'))
        content_type = ContentType.objects.get(model='project', app_label='fieldsight')
        regions = request.GET.get('regions', None)

        if edit == 0:
            response = HttpResponse(content_type='application/ms-excel')
            response['Content-Disposition'] = 'attachment; filename="bulk_upload_sites.xls"'

            wb = xlwt.Workbook(encoding='utf-8')
            ws = wb.add_sheet('Sites')

            # Sheet header, first row
            row_num = 0

            font_style = xlwt.XFStyle()
            font_style.font.bold = True

            columns = ['identifier', 'name', 'type', 'phone', 'address', 'public_desc', 'additional_desc', 'latitude', 'longitude',]
            if project.cluster_sites:
                columns += ['region_id',]
            meta_ques = project.site_meta_attributes
            for question in meta_ques:
                columns += [question['question_name']]
            for col_num in range(len(columns)):
                ws.write(row_num, col_num, columns[col_num], font_style)

            # Sheet body, remaining rows
            font_style = xlwt.XFStyle()

            wb.save(response)
            return response

        if regions:
            regions = regions.split(',')
        task_obj = CeleryTaskProgress.objects.create(user=source_user, content_object=project, task_type=8)
        if task_obj:
            task = generateSiteDetailsXls.delay(task_obj.pk, source_user, self.kwargs.get('pk'), regions)
            task_obj.task_id = task.id
            task_obj.save()
            status, data = 200, {'status':'true','message':'The sites details xls file is being generated. You will be notified after the file is generated.'}
        else:
            status, data = 401, {'status':'false','message':'Error occured please try again.'}
        return JsonResponse(data, status=status)