如何将Excel工作表从Python(Unix)保存为CSV? [英] How to save an Excel worksheet as CSV from Python (Unix)?

查看:177
本文介绍了如何将Excel工作表从Python(Unix)保存为CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个Python脚本,读入Excel电子表格并将其工作表中的一些作为CSV文件保存。



我该怎么做? >

谢谢!



PS:我发现第三方模块,用于从Python读取和写入Excel文件,但据我所知,他们只能以Excel格式保存文件(即* .xls)格式。如果我在这里错了,一些示例代码显示如何做这些模块,我将不胜感激。



我也遇到了一个解决方案,我不能很明白,但似乎是Windows特定的,因此无论如何也不会帮助我,因为我想在Unix中这样做。无论如何,我不清楚这个解决方案可以扩展到我想要做的,甚至在Windows下。

p>使用这两个库的最基本的例子是逐行描述:


  1. 打开xls工作簿

  2. 引用第一个电子表格

  3. 打开二进制写入目标csv文件

  4. 创建默认的csv writer对象

  5. 循环第一个电子表格的所有行

  6. 将行转储到csv



< hr>

  import xlrd 
import csv

with xlrd.open_workbook('a_file.xls')as wb:
sh = wb.sheet_by_index(0)#或wb.sheet_by_name('name_of_the_sheet_here')
with open('a_file.csv','wb')as f:
c = csv (f)
for r in range(sh.nrows):
c.writerow(sh.row_values(r))






  import openpyxl 
import csv

wb = openpyxl.load_workbook('test.xlsx')
sh = wb.get_active_sheet()
打开('test.csv','wb')as f:
c = csv.writer(f)
在sh.rows中的r:
c.writerow([cell.value for cell在r])


I want to write a Python script that reads in an Excel spreadsheet and saves some of its worksheets as CSV files.

How can I do this?

Thanks!

PS: I have found third-party modules for reading and writing Excel files from Python, but as far as I can tell, they can only save files in Excel (i.e. *.xls) format. If I'm wrong here, some example code showing how to do what I'm trying to do with these modules would be appreciated.

I also came across one solution that I can't quite understand, but seems to be Windows-specific, and therefore would not help me anyway, since I want to do this in Unix. At any rate, it's not clear to me that this solution can be extended to do what I want to do, even under Windows.

解决方案

The most basic exemples using the two libraries described line by line:

  1. Open the xls workbook
  2. Reference the first spreadsheet
  3. Open in binary write the target csv file
  4. Create the default csv writer object
  5. Loop over all the rows of the first spreadsheet
  6. Dump the rows into the csv


import xlrd
import csv

with xlrd.open_workbook('a_file.xls') as wb:
    sh = wb.sheet_by_index(0)  # or wb.sheet_by_name('name_of_the_sheet_here')
    with open('a_file.csv', 'wb') as f:
        c = csv.writer(f)
        for r in range(sh.nrows):
            c.writerow(sh.row_values(r))


import openpyxl
import csv

wb = openpyxl.load_workbook('test.xlsx')
sh = wb.get_active_sheet()
with open('test.csv', 'wb') as f:
    c = csv.writer(f)
    for r in sh.rows:
        c.writerow([cell.value for cell in r])

这篇关于如何将Excel工作表从Python(Unix)保存为CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆