读excel
python提供了三种方法读取excel
1、xlrd确定是只支持excel2003以下版本,跨平台
2、openpyxl只支持excel2007版本,跨平台
3、pywin32支持所有版本,只能在windows系统上使用
import win32com.client
xlsapp=win32com.client.Dispatch("Excel.Application")
xlsbook=xlsapp.Workbooks.open("E:\\shf.xlsx")
xlssheet=xlsbook.sheets("sheet1")
rs=xlssheet.usedrange.rows
写excel
这里介绍一个不错的包xlwt,可以工作在任何平台。这也就意味着你可以在Linux下保存Excel文件。
基本部分
在写入Excel表格之前,你必须初始化workbook对象,然后添加一个workbook对象。比如:
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')
这样表单就被创建了,写入数据也很简单:
# indexing is zero based, row then column
sheet.write(0,1,'test text')
之后,就可以保存文件(这里不需要想打开文件一样需要close文件):
wbk.save('test.xls')
深入探索
worksheet对象,当你更改表单内容的时候,会有警告提示。
sheet.write(0,0,'test')
sheet.write(0,0,'oops')
# returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0
解决方式:使用cell_overwrite_ok=True来创建worksheet:
sheet2 = wbk.add_sheet('sheet 2', cell_overwrite_ok=True)
sheet2.write(0,0,'some text')
sheet2.write(0,0,'this should overwrite')
这样你就可以更改表单2的内容了。
更多
# Initialize a style
style = xlwt.XFStyle()
# Create a font to use with the style
font = xlwt.Font()
font.name = 'Times New Roman'
font.bold = True
# Set the style's font to this new one you set up
style.font = font
# Use the style when writing
sheet.write(0, 0, 'some bold Times text', style)
xlwt 允许你每个格子或者整行地设置格式。还可以允许你添加链接以及公式。其实你可以阅读源代码,那里有很多例子:
dates.py, 展示如何设置不同的数据格式
hyperlinks.py, 展示如何创建超链接 (hint: you need to use a formula)
merged.py, 展示如何合并格子
row_styles.py, 展示如何应用Style到整行格子中.
在写入Excel表格之前,你必须初始化workbook对象,然后添加一个workbook对象。比如:
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')
这样表单就被创建了,写入数据也很简单:
# indexing is zero based, row then column
sheet.write(0,1,'test text')
之后,就可以保存文件(这里不需要想打开文件一样需要close文件):
wbk.save('test.xls')
深入探索
worksheet对象,当你更改表单内容的时候,会有警告提示。
sheet.write(0,0,'test')
sheet.write(0,0,'oops')
# returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0
解决方式:使用cell_overwrite_ok=True来创建worksheet:
sheet2 = wbk.add_sheet('sheet 2', cell_overwrite_ok=True)
sheet2.write(0,0,'some text')
sheet2.write(0,0,'this should overwrite')
这样你就可以更改表单2的内容了。
更多
# Initialize a style
style = xlwt.XFStyle()
# Create a font to use with the style
font = xlwt.Font()
font.name = 'Times New Roman'
font.bold = True
# Set the style's font to this new one you set up
style.font = font
# Use the style when writing
sheet.write(0, 0, 'some bold Times text', style)
xlwt 允许你每个格子或者整行地设置格式。还可以允许你添加链接以及公式。其实你可以阅读源代码,那里有很多例子:
dates.py, 展示如何设置不同的数据格式
hyperlinks.py, 展示如何创建超链接 (hint: you need to use a formula)
merged.py, 展示如何合并格子
row_styles.py, 展示如何应用Style到整行格子中.