Python保留前10行的Excel文件

时间:2015-08-17 07:10:35

标签: python excel

Windows 7 + Python 2.76

结构为20行和6列的Excel文件。

我希望新文件只保留在前10行(对应的6列)中。

这是一个好方法吗?

old_file = open_workbook(“c:\\the_file.xls”,formatting_info=True)
old_sheet = old_file.sheet_by_index(0)

new_file = xlwt.Workbook(encoding='utf-8', style_compression = 0)
new_sheet = new_file.add_sheet('Sheet1', cell_overwrite_ok = True)

columns0 = []
columns1 = []
columns2 = []
columns3 = []
columns4 = []
columns5 = []

for row in range(10):

    column_0 = old_sheet.cell(row,0).value
    column_1 = old_sheet.cell(row,1).value
    column_2 = old_sheet.cell(row,2).value
    column_3 = old_sheet.cell(row,3).value
    column_4 = old_sheet.cell(row,4).value
    column_5 = old_sheet.cell(row,5).value

columns0.append(column_0)
columns1.append(column_1)
columns2.append(column_2)
columns3.append(column_3)
columns4.append(column_4)
columns5.append(column_5)

for b0, content0 in enumerate(columns0):
    new_sheet.write(b0, 0, content0)

for b1, content1 in enumerate(columns1):
    new_sheet.write(b1, 1, content1)

for b2, content2 in enumerate(columns2):
    new_sheet.write(b2, 2, content2)

for b3, content3 in enumerate(columns3):
    new_sheet.write(b3, 3, content3)

for b4, content4 in enumerate(columns4):
    new_sheet.write(b4, 4, content4)

for b5, content5 in enumerate(columns5):
    new_sheet.write(b5, 5, content5)

new_file.save("C:\\new_file.xls")

它有效,但代码看起来并不整洁。

什么是更好的方式?

2 个答案:

答案 0 :(得分:1)

不,这不是一个好方法,这是循环的用例,示例 -

old_file = open_workbook(each_file,formatting_info=True)
old_sheet = old_file.sheet_by_index(0)

new_file = xlwt.Workbook(encoding='utf-8', style_compression = 0)
new_sheet = new_file.add_sheet('Sheet1', cell_overwrite_ok = True)

for row in range(10):
    for col in range(6):
        new_sheet.write(row,col,old_sheet.cell(row,col).value)

答案 1 :(得分:1)

使用pandas更简单:

import pandas as pd
orig_df = pd.read_excel(orig_excel_path, sheetname=sheetname)
orig_df.head(10).to_excel(new_excel_path, sheet_name=new_sheetname)