Python URL命令导出到.xlsx文件

时间:2017-10-20 13:00:36

标签: python django excel

我有一个命令可以提供我项目的所有网址。我想将此命令导出到xlsx文件。有任何想法吗?在打印消息中应该是url命令

提前谢谢你们。

urls.py (此处提供所有网址的命令)

from django.conf.urls import RegexURLPattern, RegexURLResolver
from django.core import urlresolvers
from django.core.management import BaseCommand


class Command(BaseCommand):
    def add_arguments(self, parser):

        pass

    def handle(self, *args, **kwargs):

        urls = urlresolvers.get_resolver()
        all_urls = list()

        def func_for_sorting(i):
            if i.name is None:
                i.name = ''
            return i.name

        def show_urls(urls):
            for url in urls.url_patterns:
                if isinstance(url, RegexURLResolver):
                    show_urls(url)
                elif isinstance(url, RegexURLPattern):
                    all_urls.append(url)

        show_urls(urls)

        all_urls.sort(key=func_for_sorting, reverse=False)
        print('Total urls:', len(all_urls))
        print('-' * 220)
        for url in all_urls:
            print('| {0.regex.pattern:100} | {0.name:50} | {0.lookup_str:70} |'.format(url))
        print('-' * 220)

export_test.py (导出命令)

import xlsxwriter

# Create a workbook and add a worksheet
workbook = xlsxwriter.Workbook('Test2.xlsx')
worksheet = workbook.add_worksheet()

# Add a bold format

bold = workbook.add_format({'bold': True})
# Write header

worksheet.write('A1', 'URL', bold)
worksheet.write('B1', 'Class', bold)


expanses = (
    ['TestUrl.com', 'TestClass'],
    ['TestUrl2.com', 'ExcelClass'],
    ['TestUrl3.com', 'OrderClass'],
    ['TestUrl4.com', 'TransferClass'],
)
row = 1
col = 0

for item, cost in (expanses):
    worksheet.write(row, col,   item)
    worksheet.write(row, col + 1, cost)
    row += 1

workbook.close()

我认为它应该在打印消息中

1 个答案:

答案 0 :(得分:2)

我可能在这里误解了你,但是如果你想从命令导出到xlsx文件,那么只需替换打印url的行将其导出到xlsx文件。

row = 0
for url in all_urls:
  worksheet.write(row, 0, url)
  row += 1

(您还需要将export_test.py中的代码位添加到相应位置的urls.py文件中,例如打开并关闭工作簿,添加工作表,导入xlsxwriter。)