python脚本实现xls(xlsx)转成csv

yipeiwu_com5年前Python基础

# xls_csv

把xls,xlsx格式的文档转换成csv格式

# 使用
python xls2csv.py <xls or xlsx file path>

# -*- coding: utf-8 -*-
import xlrd
import xlwt
import sys
from datetime import date,datetime
 
def read_excel(filename):
 
  workbook = xlrd.open_workbook(filename)
  # print sheet2.name,sheet2.nrows,sheet2.ncols
  sheet2 = workbook.sheet_by_index(0)
  
  for row in xrange(0, sheet2.nrows):
    rows = sheet2.row_values(row)
    def _tostr(cell):
      if type(u'') == type(cell): 
        return "\"%s\"" % cell.encode('utf8')
      else:
        return "\"%s\"" % str(cell) 
  
    print ','.join([_tostr(cell) for cell in rows ])
  
if __name__ == '__main__':
  filename = sys.argv[1]
  read_excel(filename)

再给大家分享一则代码

xlsx文件解析处理:openpyxl库 csv文件格式生成:csv

python#coding: utf-8
# 依赖openpyxl库:http://openpyxl.readthedocs.org/en/latest/

from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl.cell import get_column_letter
from openpyxl import load_workbook
import csv
import os
import sys

def xlsx2csv(filename):
try:
 xlsx_file_reader = load_workbook(filename=filename)
 for sheet in xlsx_file_reader.get_sheet_names():
 # 每个sheet输出到一个csv文件中,文件名用xlsx文件名和sheet名用'_'连接
 csv_filename = '{xlsx}_{sheet}.csv'.format(
 xlsx=os.path.splitext(filename.replace(' ', '_'))[0],
 sheet=sheet.replace(' ', '_'))

 csv_file = file(csv_filename, 'wb')
 csv_file_writer = csv.writer(csv_file)

 sheet_ranges = xlsx_file_reader[sheet]
 for row in sheet_ranges.rows:
 row_container = []
 for cell in row:
 if type(cell.value) == unicode:
row_container.append(cell.value.encode('utf-8'))
else:
row_container.append(str(cell.value))
csv_file_writer.writerow(row_container)
csv_file.close()

 except Exception as e:
print(e)

if __name__ == '__main__':
 if len(sys.argv) != 2:
 print('usage: xlsx2csv <xlsx file name>')
else:
xlsx2csv(sys.argv[1])
sys.exit(0)

相关文章

如何用Python实现简单的Markdown转换器

如何用Python实现简单的Markdown转换器

今天心血来潮,写了一个 Markdown 转换器。 import os, re,webbrowser text = ''' # TextHeader ## Header1 Li...

利用python求积分的实例

python的numpy库集成了很多的函数。利用其中的函数可以很方便的解决一些数学问题。本篇介绍如何使用python的numpy来求解积分。 代码如下: # -*- coding:...

python从list列表中选出一个数和其对应的坐标方法

python从list列表中选出一个数和其对应的坐标方法

例1:给一个列表如下,里面每个元素对应的是x和y的值 a = [[5,2],[6,3],[8,8],[1,3]] 现在要挑出y的值为3对应的x的值,即6和1 import nu...

对PyQt5基本窗口控件 QMainWindow的使用详解

对PyQt5基本窗口控件 QMainWindow的使用详解

QMainWindow基本介绍 QMainWindow主窗口为用户提供了一个应用程序框架,它有自己的布局,可以在布局中添加控件。 窗口类型介绍 PyQt5中,主要使用以下三个类来创建窗...

python3.3教程之模拟百度登陆代码分享

复制代码 代码如下:#-*-coding:utf-8-*-'''Created on 2014年1月10日 @author: hhdys'''import urllib.request,...