python 读取xlsx,写入xls

# -*- coding: utf-8 -*-
import xlrd
import xlwt
import os
import json
import sys
#import codecs

# 读取xlsx,生成query列表[[],..,[]]
def read_xlsx(xlsx_input_file):
  xlsx_open_file = xlrd.open_workbook(xlsx_input_file)
  sheet_names = xlsx_open_file.sheet_names()
  print(sheet_names) # ['1']
  xlsx_querys = []
  sheetnum = 0
  xlsx_table = xlsx_open_file.sheet_by_index(sheetnum)
  count_xlsx = 0
  for xlsx_row in xlsx_table.get_rows():
      query_value = xlsx_row[0].value.strip()
      xlsx_querys.append([query_value])
      count_xlsx += 1 
      print(query_value)
  print(xlsx_querys)
  # [['qqq'], ['www'], 
  # ['eee'], ['rrr'], ['ttt']]
  print('count_xlsx=', count_xlsx,'  len(xlsx_querys)=' ,len(xlsx_querys))
  return xlsx_querys

# 将[[query, True],..,[query, False]]写入xls
def write2xls(out_diffs, xls_output_file):
  not_exit_que_wb = xlwt.Workbook(encoding = 'ascii') #open a excel
  not_exit_que_ws1 = not_exit_que_wb.add_sheet('checkdiff') #添加一个新表
  not_exit_que_row = 0 #写入的起始行
  not_exit_que_col = 0 #写入的起始列
  for item in out_diffs:
      not_exit_que_ws1.write(not_exit_que_row, not_exit_que_col , item[0])
      not_exit_que_ws1.write(not_exit_que_row, not_exit_que_col+1 , item[1])
      not_exit_que_row += 1
  not_exit_que_wb.save(xls_output_file)
  print('not_exit_que_row=', not_exit_que_row)
  return True
 

def checkingdiff_w2xls(xlsx_input_file, xls_output_file):
  xlsx_querys = read_xlsx(xlsx_input_file)
  # 构造out_diffs
  for i in range(len(xlsx_querys)):
    xlsx_querys[i].extend(['True'])
  print(xlsx_querys) # [['qqq', 'True'], ['www', 'True'],
  # ['eee', 'True'], ['rrr', 'True'], ['ttt', 'True']]
  write2xls(xlsx_querys, xls_output_file)
  return True

if __name__=="__main__":
  # query = sys.argv[1]
  # checkflag = checkingdiff(query)
  # print("query={} diff={}".format(query, checkflag))
  query_xlsx = sys.argv[1]
  xls_output_file = sys.argv[2]
  checkingdiff_w2xls(query_xlsx, xls_output_file)

可能有用:https://blog.csdn.net/qq_45779334/article/details/112172895
环境准备
需要下载xlrd==1.2.0版本,因为目前xlrd更新到了2.0.1版本,只支持.xls文件。
所以如果需要读取.xlsx文件,需要安装旧版本。

#如果之前安装过,需要卸载原先版本
pip uninstall xlrd
#下载1.2.0版本
pip install xlrd==1.2.0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值