2017-10-20 88 views
2

我有一個命令可以顯示我的項目的所有URL。我想將這個命令導出到xlsx文件。有任何想法嗎?在打印留言應該是網址命令Python URL命令導出爲.xlsx文件

謝謝各位提前。

urls.py(以下命令,讓所有URL)

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() 

我想應該是在印刷消息

+0

你可以直接將你的命令寫入csv文件,爲什麼你需要一個相同的導出腳本。一旦你收到與它相關的所有URL和類名,它只是一個csv編寫器的問題,你可以參考'https:// docs.python.org/2/library/csv.html'。你不需要安裝'xlsxwriter' –

回答

2

我在這裏可能會誤解你,但是如果你想從命令輸出到xlsx文件,t如果只是替換打印網址的行,將其導出到xlsx文件。

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

(你還需要從export_test.py在適當的地方,比如打開添加代碼的位向urls.py文件並關閉工作簿,添加一個工作表,進口xlsxwriter。)