python指令碼實現xls(xlsx)轉成csv

來源:互聯網
上載者:User
# xls_csv

把xls,xlsx格式的文檔轉換成csv格式

# 使用
python xls2csv.py

# -*- coding: utf-8 -*-import xlrdimport xlwtimport sysfrom 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 Workbookfrom openpyxl.compat import rangefrom openpyxl.cell import get_column_letterfrom openpyxl import load_workbookimport csvimport osimport sysdef 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 ')else:xlsx2csv(sys.argv[1])sys.exit(0)
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.