search
HomeBackend DevelopmentPython Tutorialpython脚本实现xls(xlsx)转成csv

# xls_csv

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

# 使用
python xls2csv.py

# -*- 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)

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools