PythonはExcelのある列を読み取る|jsonを転送する

8869 ワード

import xlrd

worksheet = xlrd.open_workbook(u'  .xlsx')
sheet_names= worksheet.sheet_names()
print(sheet_names)
for sheet_name in sheet_names:
    sheet = worksheet.sheet_by_name(sheet_name)
    rows = sheet.nrows #     
    cols = sheet.ncols #     ,     
    all_content = []
    for i in range(rows) :
        cell = sheet.cell_value(i, 2) #       
        try:
            cell = int(cell) #      
            all_content.append(cell)
        except ValueError as e:
            pass
    # cols = sheet.col_values(2) #                 float
    print(all_content)

バージョンをアップグレードし、テーブルをjsonでファイルに出力
import xlrd
import json
from datetime import datetime
from xlrd import xldate_as_tuple

worksheet = xlrd.open_workbook(u'text.xlsx')
sheet_names= worksheet.sheet_names()
print(sheet_names)
for sheet_name in sheet_names:
    sheet = worksheet.sheet_by_name(sheet_name)
    rows = sheet.nrows #     
    cols = sheet.ncols #     ,
    all_content = {}
    for i in range(rows) :
        crmid = ''
        for j in range(cols):
            cell = sheet.cell_value(i, j) #
            ctype = sheet.cell(i, j).ctype
            if j==0 :
                try:
                    id = int(cell)  #        
                except ValueError as e:
                    id = cell
                all_content[id] = []
            
            if ctype ==3: #              
                date = datetime(*xldate_as_tuple(cell, 0))
                cell = date.strftime('%Y-%n-%d')
            else:
                pass
            
            all_content[id].append(cell)
    res = json.dumps(all_content)
    with open('test.txt', 'a') as f:
        f.write(res) #         ,         print    
    print (res)